hash
stringlengths 40
40
| date
stringdate 2017-08-30 22:37:25
2025-03-22 03:08:47
| author
stringclasses 173
values | commit_message
stringlengths 15
151
| is_merge
bool 1
class | masked_commit_message
stringlengths 6
126
| type
stringclasses 17
values | git_diff
stringlengths 182
1.51M
⌀ |
|---|---|---|---|---|---|---|---|
35db2785d3faceef0c8936e6f46ef84004d6b181
|
2021-09-16 02:19:21
|
Evan Purkhiser
|
style(js): Correct comment on useTeams (#28609)
| false
|
Correct comment on useTeams (#28609)
|
style
|
diff --git a/static/app/utils/useTeams.tsx b/static/app/utils/useTeams.tsx
index ec824cd0363e5f..343a3ba0234005 100644
--- a/static/app/utils/useTeams.tsx
+++ b/static/app/utils/useTeams.tsx
@@ -42,8 +42,9 @@ export type Result = {
teams: Team[];
/**
* This is an action provided to consumers for them to update the current
- * teams result set using a simple search query. You can allow the new
- * results to either be appended or replace the existing results.
+ * teams result set using a simple search query.
+ *
+ * Will always add new options into the store.
*/
onSearch: (searchTerm: string) => Promise<void>;
} & Pick<State, 'fetching' | 'hasMore' | 'fetchError'>;
|
fee6b053b00a8cdb7c43148243dea46440a87428
|
2021-06-24 13:47:38
|
Priscila Oliveira
|
fix(app-store-connect): Fix closeModal + refresh on save (#26828)
| false
|
Fix closeModal + refresh on save (#26828)
|
fix
|
diff --git a/static/app/actionCreators/modal.tsx b/static/app/actionCreators/modal.tsx
index 7c1961878ce758..15004aab35fc90 100644
--- a/static/app/actionCreators/modal.tsx
+++ b/static/app/actionCreators/modal.tsx
@@ -196,7 +196,7 @@ export type SentryAppDetailsModalOptions = {
type DebugFileSourceModalOptions = {
sourceType: DebugFileSource;
- onSave: (data: Record<string, any>) => void;
+ onSave: (data: Record<string, any>) => Promise<void>;
appStoreConnectContext?: AppStoreConnectContextProps;
onClose?: () => void;
sourceConfig?: Record<string, any>;
diff --git a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/index.tsx b/static/app/components/modals/debugFileCustomRepository/appStoreConnect/index.tsx
index d40ee921c8f260..d1394bdf4b02ef 100644
--- a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/index.tsx
+++ b/static/app/components/modals/debugFileCustomRepository/appStoreConnect/index.tsx
@@ -45,7 +45,7 @@ type ItunesRevalidationSessionContext = SessionContext & {
itunes_session: string;
};
-type IntialData = {
+type InitialData = {
appId: string;
appName: string;
appconnectIssuer: string;
@@ -68,10 +68,10 @@ type Props = Pick<ModalRenderProps, 'Header' | 'Body' | 'Footer'> & {
api: Client;
orgSlug: Organization['slug'];
projectSlug: Project['slug'];
- onSubmit: (data: IntialData) => void;
+ onSubmit: (data: InitialData) => void;
location: Location;
appStoreConnectContext?: AppStoreConnectContextProps;
- initialData?: IntialData;
+ initialData?: InitialData;
};
const steps = [
@@ -263,7 +263,7 @@ function AppStoreConnect({
sessionContext: newSessionContext ?? sessionContext,
},
});
- onSubmit(response as IntialData);
+ onSubmit(response as InitialData);
} catch (error) {
setIsLoading(false);
addErrorMessage(errorMessage);
diff --git a/static/app/components/modals/debugFileCustomRepository/index.tsx b/static/app/components/modals/debugFileCustomRepository/index.tsx
index 0918918d922f75..9e6c4c2b743fa8 100644
--- a/static/app/components/modals/debugFileCustomRepository/index.tsx
+++ b/static/app/components/modals/debugFileCustomRepository/index.tsx
@@ -27,7 +27,7 @@ type Props = WithRouterProps<RouteParams, {}> & {
/**
* Callback invoked with the updated config value.
*/
- onSave: (config: Record<string, any>) => void;
+ onSave: (data: Record<string, any>) => Promise<void>;
/**
* Type of this source.
*/
@@ -38,7 +38,7 @@ type Props = WithRouterProps<RouteParams, {}> & {
* The sourceConfig. May be empty to create a new one.
*/
sourceConfig?: Record<string, any>;
-} & Pick<ModalRenderProps, 'Header' | 'Body' | 'Footer'>;
+} & Pick<ModalRenderProps, 'Header' | 'Body' | 'Footer' | 'closeModal'>;
function DebugFileCustomRepository({
Header,
@@ -50,9 +50,19 @@ function DebugFileCustomRepository({
params: {orgId, projectId: projectSlug},
location,
appStoreConnectContext,
+ closeModal,
}: Props) {
function handleSave(data: Record<string, any>) {
- onSave({...data, type: sourceType});
+ onSave({...data, type: sourceType}).then(() => {
+ closeModal();
+
+ if (
+ sourceType === 'appStoreConnect' &&
+ appStoreConnectContext?.updateAlertMessage
+ ) {
+ window.location.reload();
+ }
+ });
}
if (sourceType === 'appStoreConnect') {
diff --git a/static/app/views/settings/projectDebugFiles/externalSources/symbolSources.tsx b/static/app/views/settings/projectDebugFiles/externalSources/symbolSources.tsx
index fb27205c39bc8a..7b37b6ba319a47 100644
--- a/static/app/views/settings/projectDebugFiles/externalSources/symbolSources.tsx
+++ b/static/app/views/settings/projectDebugFiles/externalSources/symbolSources.tsx
@@ -5,7 +5,7 @@ import {Location} from 'history';
import omit from 'lodash/omit';
import {addErrorMessage, addSuccessMessage} from 'app/actionCreators/indicator';
-import {closeModal, openDebugFileSourceModal} from 'app/actionCreators/modal';
+import {openDebugFileSourceModal} from 'app/actionCreators/modal';
import ProjectActions from 'app/actions/projectActions';
import {Client} from 'app/api';
import Feature from 'app/components/acl/feature';
@@ -23,6 +23,7 @@ import {IconRefresh, IconWarning} from 'app/icons';
import {t, tct, tn} from 'app/locale';
import space from 'app/styles/space';
import {Organization, Project} from 'app/types';
+import {defined} from 'app/utils';
import Field from 'app/views/settings/components/forms/field';
import RichListField from 'app/views/settings/components/forms/richListField';
import TextBlock from 'app/views/settings/components/text/textBlock';
@@ -210,20 +211,21 @@ function SymbolSources({
sourceConfig,
sourceType: item.type,
appStoreConnectContext,
- onSave: updatedData => handleUpdateSymbolSource(updatedData as Item, itemIndex),
- onClose: handleCloseImageDetailsModal,
+ onSave: updatedItem =>
+ handleSaveModal({updatedItem: updatedItem as Item, index: itemIndex}),
+ onClose: handleCloseModal,
});
}
- function getRequestMessages(symbolSourcesQuantity: number) {
- if (symbolSourcesQuantity > symbolSources.length) {
+ function getRequestMessages(updatedSymbolSourcesQuantity: number) {
+ if (updatedSymbolSourcesQuantity > symbolSources.length) {
return {
successMessage: t('Successfully added custom repository'),
errorMessage: t('An error occurred while adding a new custom repository'),
};
}
- if (symbolSourcesQuantity < symbolSources.length) {
+ if (updatedSymbolSourcesQuantity < symbolSources.length) {
return {
successMessage: t('Successfully removed custom repository'),
errorMessage: t('An error occurred while removing the custom repository'),
@@ -236,50 +238,53 @@ function SymbolSources({
};
}
- async function handleChange(updatedSymbolSources: Item[], updatedItem?: Item) {
- const symbolSourcesWithoutErrors = updatedSymbolSources.map(updatedSymbolSource =>
- omit(updatedSymbolSource, ['error', 'warning'])
- );
+ function handleSaveModal({
+ updatedItems,
+ updatedItem,
+ index,
+ }: {
+ updatedItems?: Item[];
+ updatedItem?: Item;
+ index?: number;
+ }) {
+ let items = updatedItems ?? [];
+
+ if (updatedItem && defined(index)) {
+ items = [...symbolSources] as Item[];
+ items.splice(index, 1, updatedItem);
+ }
- const {successMessage, errorMessage} = getRequestMessages(
- updatedSymbolSources.length
+ const symbolSourcesWithoutErrors = items.map(item =>
+ omit(item, ['error', 'warning'])
);
- const expandedSymbolSourceKeys = symbolSourcesWithoutErrors.map(expandKeys);
+ const {successMessage, errorMessage} = getRequestMessages(items.length);
- try {
- const updatedProjectDetails: Project = await api.requestPromise(
- `/projects/${organization.slug}/${projectSlug}/`,
- {
- method: 'PUT',
- data: {
- symbolSources: JSON.stringify(expandedSymbolSourceKeys),
- },
- }
- );
+ const expandedSymbolSourceKeys = symbolSourcesWithoutErrors.map(expandKeys);
- ProjectActions.updateSuccess(updatedProjectDetails);
- addSuccessMessage(successMessage);
- closeModal();
- if (updatedItem && updatedItem.type === 'appStoreConnect') {
- // TODO(Priscila): check the reason why the closeModal doesn't call the function
- // handleCloseImageDetailsModal when revalidating
- handleCloseImageDetailsModal();
- reloadPage();
+ const promise: Promise<any> = api.requestPromise(
+ `/projects/${organization.slug}/${projectSlug}/`,
+ {
+ method: 'PUT',
+ data: {
+ symbolSources: JSON.stringify(expandedSymbolSourceKeys),
+ },
}
- } catch {
- closeModal();
+ );
+
+ promise.catch(() => {
addErrorMessage(errorMessage);
- }
- }
+ });
- function handleUpdateSymbolSource(updatedItem: Item, index: number) {
- const items = [...symbolSources] as Item[];
- items.splice(index, 1, updatedItem);
- handleChange(items, updatedItem);
+ promise.then(result => {
+ ProjectActions.updateSuccess(result);
+ addSuccessMessage(successMessage);
+ });
+
+ return promise;
}
- function handleOpenDebugFileSourceModalToEdit(repositoryId: string) {
+ function handleEditModal(repositoryId: string) {
router.push({
...location,
query: {
@@ -289,13 +294,7 @@ function SymbolSources({
});
}
- function reloadPage() {
- if (appStoreConnectContext && appStoreConnectContext.updateAlertMessage) {
- window.location.reload();
- }
- }
-
- function handleCloseImageDetailsModal() {
+ function handleCloseModal() {
router.push({
...location,
query: {
@@ -361,23 +360,24 @@ function SymbolSources({
addButtonText={t('Add Repository')}
name="symbolSources"
value={value}
- onChange={handleChange}
+ onChange={(updatedItems: Item[]) => {
+ handleSaveModal({updatedItems});
+ }}
renderItem={item => (
<TextOverflow>{item.name ?? t('<Unnamed Repository>')}</TextOverflow>
)}
disabled={!organization.features.includes('custom-symbol-sources')}
formatMessageValue={false}
- onAddItem={(item, addItem) =>
+ onEditItem={item => handleEditModal(item.id)}
+ onAddItem={(item, addItem) => {
openDebugFileSourceModal({
sourceType: item.value,
- onSave: addItem,
- })
- }
- onEditItem={item => handleOpenDebugFileSourceModalToEdit(item.id)}
+ onSave: updatedData => Promise.resolve(addItem(updatedData as Item)),
+ });
+ }}
removeConfirm={{
onConfirm: item => {
if (item.type === 'appStoreConnect') {
- handleCloseImageDetailsModal();
window.location.reload();
}
},
|
1aaa2380215cc19711c9177ba1c2075061d9a665
|
2021-04-30 03:01:45
|
William Mak
|
fix(trace-view): Support multiple roots for the trace view (#25734)
| false
|
Support multiple roots for the trace view (#25734)
|
fix
|
diff --git a/bin/mock-traces b/bin/mock-traces
index 0bf1e494df062b..e8ffb756d6c5c2 100755
--- a/bin/mock-traces
+++ b/bin/mock-traces
@@ -158,6 +158,29 @@ def main(slow=False):
],
},
)
+ print(f" > Loading trace with many roots") # NOQA
+ trace_id = uuid4().hex
+ for _ in range(15):
+ create_trace(
+ slow,
+ timestamp - timedelta(milliseconds=random_normal(4000, 250, 1000)),
+ timestamp,
+ generate_user(),
+ trace_id,
+ None,
+ {
+ "project": frontend_project,
+ "transaction": "/multiple-root/:root/",
+ "frontend": True,
+ "children": [
+ {
+ "project": backend_project,
+ "transaction": "/multiple-root/child/",
+ "children": [],
+ }
+ ],
+ },
+ )
print(f" > Loading chained trace with orphans") # NOQA
trace_id = uuid4().hex
diff --git a/src/sentry/api/endpoints/organization_events_trace.py b/src/sentry/api/endpoints/organization_events_trace.py
index c0568c14a79d2e..7a4b288fedd836 100644
--- a/src/sentry/api/endpoints/organization_events_trace.py
+++ b/src/sentry/api/endpoints/organization_events_trace.py
@@ -355,24 +355,22 @@ def get(self, request: HttpRequest, organization: Organization, trace_id: str) -
warning_extra: Dict[str, str] = {"trace": trace_id, "organization": organization}
- root = transactions[0] if is_root(transactions[0]) else None
-
- # Look for extra roots
- extra_roots = 0
- for item in transactions[1:]:
+ # Look for the roots
+ roots: List[SnubaTransaction] = []
+ for item in transactions:
if is_root(item):
- extra_roots += 1
+ roots.append(item)
else:
break
- if extra_roots > 0:
+ if len(roots) > 1:
sentry_sdk.set_tag("discover.trace-view.warning", "root.extra-found")
logger.warning(
"discover.trace-view.root.extra-found",
- {"extra_roots": extra_roots, **warning_extra},
+ {"extra_roots": len(roots), **warning_extra},
)
return Response(
- self.serialize(transactions, errors, root, warning_extra, event_id, detailed)
+ self.serialize(transactions, errors, roots, warning_extra, event_id, detailed)
)
@@ -430,7 +428,7 @@ def serialize(
self,
transactions: Sequence[SnubaTransaction],
errors: Sequence[SnubaError],
- root: Optional[SnubaTransaction],
+ roots: Sequence[SnubaTransaction],
warning_extra: Dict[str, str],
event_id: Optional[str],
detailed: bool = False,
@@ -446,31 +444,38 @@ def serialize(
root_id: Optional[str] = None
with sentry_sdk.start_span(op="building.trace", description="light trace"):
- # We might not be necessarily connected to the root if we're on an orphan event
- if root is not None and root["id"] != snuba_event["id"]:
- # Get the root event and see if the current event's span is in the root event
- root_event = eventstore.get_event_by_id(root["project.id"], root["id"])
- root_spans: NodeSpans = root_event.data.get("spans", [])
- root_span = find_event(
- root_spans,
- lambda item: item is not None
- and item["span_id"] == snuba_event["trace.parent_span"],
- )
+ # Going to nodestore is more expensive than looping twice so check if we're on the root first
+ for root in roots:
+ if root["id"] == snuba_event["id"]:
+ current_generation = 0
+ break
- # We only know to add the root if its the direct parent
- if root_span is not None:
- # For the light response, the parent will be unknown unless it is a direct descendent of the root
- root_id = root["id"]
- trace_results.append(
- TraceEvent(
- root,
- None,
- 0,
+ if current_generation is None:
+ for root in roots:
+ # We might not be necessarily connected to the root if we're on an orphan event
+ if root["id"] != snuba_event["id"]:
+ # Get the root event and see if the current event's span is in the root event
+ root_event = eventstore.get_event_by_id(root["project.id"], root["id"])
+ root_spans: NodeSpans = root_event.data.get("spans", [])
+ root_span = find_event(
+ root_spans,
+ lambda item: item is not None
+ and item["span_id"] == snuba_event["trace.parent_span"],
)
- )
- current_generation = 1
- elif root is not None and root["id"] == snuba_event["id"]:
- current_generation = 0
+
+ # We only know to add the root if its the direct parent
+ if root_span is not None:
+ # For the light response, the parent will be unknown unless it is a direct descendent of the root
+ root_id = root["id"]
+ trace_results.append(
+ TraceEvent(
+ root,
+ None,
+ 0,
+ )
+ )
+ current_generation = 1
+ break
current_event = TraceEvent(snuba_event, root_id, current_generation)
trace_results.append(current_event)
@@ -527,7 +532,7 @@ def serialize(
self,
transactions: Sequence[SnubaTransaction],
errors: Sequence[SnubaError],
- root: Optional[SnubaTransaction],
+ roots: Sequence[SnubaTransaction],
warning_extra: Dict[str, str],
event_id: Optional[str],
detailed: bool = False,
@@ -545,9 +550,10 @@ def serialize(
# on python 3.7.
results_map: Dict[Optional[str], List[TraceEvent]] = OrderedDict()
to_check: Deque[SnubaTransaction] = deque()
- if root:
+ results_map[None] = []
+ for root in roots:
parent_events[root["id"]] = TraceEvent(root, None, 0)
- results_map[None] = [parent_events[root["id"]]]
+ results_map[None].append(parent_events[root["id"]])
to_check.append(root)
with sentry_sdk.start_span(op="building.trace", description="full trace"):
diff --git a/tests/snuba/api/endpoints/test_organization_events_trace.py b/tests/snuba/api/endpoints/test_organization_events_trace.py
index fd62396646f55e..af914f82b23a2f 100644
--- a/tests/snuba/api/endpoints/test_organization_events_trace.py
+++ b/tests/snuba/api/endpoints/test_organization_events_trace.py
@@ -296,30 +296,48 @@ def test_no_roots(self):
assert event["parent_span_id"] == parent_span_id
assert event["event_id"] == no_root_event.event_id
- def test_multiple_roots(self):
- self.create_event(
- trace=self.trace_id,
- transaction="/second_root",
- spans=[],
- parent_span_id=None,
- project_id=self.project.id,
- )
+ def test_root_event(self):
+ root_event_id = self.root_event.event_id
+
with self.feature(self.FEATURES):
response = self.client.get(
self.url,
- data={"event_id": self.root_event.event_id},
+ data={"event_id": root_event_id, "project": -1},
format="json",
)
assert response.status_code == 200, response.content
- def test_root_event(self):
- root_event_id = self.root_event.event_id
+ assert len(response.data) == 4
+ events = {item["event_id"]: item for item in response.data}
+
+ assert root_event_id in events
+ event = events[root_event_id]
+ assert event["generation"] == 0
+ assert event["parent_event_id"] is None
+ assert event["parent_span_id"] is None
+
+ for i, child_event in enumerate(self.gen1_events):
+ child_event_id = child_event.event_id
+ assert child_event_id in events
+ event = events[child_event_id]
+ assert event["generation"] == 1
+ assert event["parent_event_id"] == root_event_id
+ assert event["parent_span_id"] == self.root_span_ids[i]
+ def test_root_with_multiple_roots(self):
+ root_event_id = self.root_event.event_id
+ self.create_event(
+ trace=self.trace_id,
+ transaction="/second_root",
+ spans=[],
+ parent_span_id=None,
+ project_id=self.project.id,
+ )
with self.feature(self.FEATURES):
response = self.client.get(
self.url,
- data={"event_id": root_event_id, "project": -1},
+ data={"event_id": self.root_event.event_id},
format="json",
)
@@ -377,6 +395,48 @@ def test_direct_parent_with_children(self):
assert event["parent_event_id"] == current_event
assert event["parent_span_id"] == self.gen1_span_ids[0]
+ def test_direct_parent_with_children_and_multiple_root(self):
+ root_event_id = self.root_event.event_id
+ current_event = self.gen1_events[0].event_id
+ child_event_id = self.gen2_events[0].event_id
+ self.create_event(
+ trace=self.trace_id,
+ transaction="/second_root",
+ spans=[],
+ parent_span_id=None,
+ project_id=self.project.id,
+ )
+
+ with self.feature(self.FEATURES):
+ response = self.client.get(
+ self.url,
+ data={"event_id": current_event, "project": -1},
+ format="json",
+ )
+
+ assert response.status_code == 200, response.content
+
+ assert len(response.data) == 3
+ events = {item["event_id"]: item for item in response.data}
+
+ assert root_event_id in events
+ event = events[root_event_id]
+ assert event["generation"] == 0
+ assert event["parent_event_id"] is None
+ assert event["parent_span_id"] is None
+
+ assert current_event in events
+ event = events[current_event]
+ assert event["generation"] == 1
+ assert event["parent_event_id"] == root_event_id
+ assert event["parent_span_id"] == self.root_span_ids[0]
+
+ assert child_event_id in events
+ event = events[child_event_id]
+ assert event["generation"] == 2
+ assert event["parent_event_id"] == current_event
+ assert event["parent_span_id"] == self.gen1_span_ids[0]
+
def test_second_generation_with_children(self):
current_event = self.gen2_events[0].event_id
child_event_id = self.gen3_event.event_id
@@ -698,6 +758,40 @@ def test_bad_span_loop(self):
# We didn't even try to start the loop of spans
assert len(gen3_1["children"]) == 0
+ def test_multiple_roots(self):
+ trace_id = uuid4().hex
+ first_root = self.create_event(
+ trace=trace_id,
+ transaction="/first_root",
+ spans=[],
+ parent_span_id=None,
+ project_id=self.project.id,
+ duration=1000,
+ )
+ second_root = self.create_event(
+ trace=trace_id,
+ transaction="/second_root",
+ spans=[],
+ parent_span_id=None,
+ project_id=self.project.id,
+ duration=500,
+ )
+ self.url = reverse(
+ self.url_name,
+ kwargs={"organization_slug": self.project.organization.slug, "trace_id": trace_id},
+ )
+ with self.feature(self.FEATURES):
+ response = self.client.get(
+ self.url,
+ data={"project": -1},
+ format="json",
+ )
+
+ assert response.status_code == 200, response.content
+ assert len(response.data) == 2
+ self.assert_event(response.data[0], first_root, "first_root")
+ self.assert_event(response.data[1], second_root, "second_root")
+
def test_sibling_transactions(self):
""" More than one transaction can share a parent_span_id """
gen3_event_siblings = [
|
425a2d8cdfe89b31c3c049973b44645dcf00e349
|
2024-02-15 01:53:08
|
Pierre Massat
|
ref(metrics_summaries): Reflect changes to match the new consumer (#65177)
| false
|
Reflect changes to match the new consumer (#65177)
|
ref
|
diff --git a/src/sentry/testutils/cases.py b/src/sentry/testutils/cases.py
index 098aecf7f9cb13..44f4fa940741cf 100644
--- a/src/sentry/testutils/cases.py
+++ b/src/sentry/testutils/cases.py
@@ -1347,11 +1347,39 @@ def store_spans(self, spans):
== 200
)
- def store_metric_summary(self, metric_summary):
+ def store_metrics_summary(self, span):
+ common_fields = {
+ "duration_ms": span["duration_ms"],
+ "end_timestamp": (span["start_timestamp_ms"] + span["duration_ms"]) / 1000,
+ "group": span["sentry_tags"].get("group", "0"),
+ "is_segment": span["is_segment"],
+ "project_id": span["project_id"],
+ "received": span["received"],
+ "retention_days": span["retention_days"],
+ "segment_id": span.get("segment_id", "0"),
+ "span_id": span["span_id"],
+ "trace_id": span["trace_id"],
+ }
+ rows = []
+ for mri, summaries in span.get("_metrics_summary", {}).items():
+ for summary in summaries:
+ rows.append(
+ {
+ **common_fields,
+ **{
+ "count": summary.get("count", 0),
+ "max": summary.get("max", 0.0),
+ "mri": mri,
+ "min": summary.get("min", 0.0),
+ "sum": summary.get("sum", 0.0),
+ "tags": summary.get("tags", {}),
+ },
+ }
+ )
assert (
requests.post(
settings.SENTRY_SNUBA + "/tests/entities/metrics_summaries/insert",
- data=json.dumps([metric_summary]),
+ data=json.dumps(rows),
).status_code
== 200
)
@@ -1523,7 +1551,7 @@ def store_indexed_span(
self.store_span(payload)
if "_metrics_summary" in payload:
- self.store_metric_summary(payload)
+ self.store_metrics_summary(payload)
class BaseMetricsTestCase(SnubaTestCase):
diff --git a/tests/sentry/api/endpoints/test_organization_ddm_meta.py b/tests/sentry/api/endpoints/test_organization_ddm_meta.py
index 1185881760a740..fec6eed35adbdd 100644
--- a/tests/sentry/api/endpoints/test_organization_ddm_meta.py
+++ b/tests/sentry/api/endpoints/test_organization_ddm_meta.py
@@ -333,6 +333,7 @@ def test_get_locations_with_too_many_combinations(self):
codeLocations="true",
)
+ @pytest.mark.skip("transition to new metrics summaries processor in snuba")
def test_get_metric_spans(self):
mri = "g:custom/page_load@millisecond"
@@ -421,6 +422,7 @@ def test_get_metric_spans(self):
{"spanDuration": 2, "spanOp": "rpc"},
]
+ @pytest.mark.skip("transition to new metrics summaries processor in snuba")
def test_get_metric_spans_with_environment(self):
mri = "g:custom/page_load@millisecond"
@@ -489,6 +491,7 @@ def test_get_metric_spans_with_environment(self):
assert len(metric_spans) == 1
assert metric_spans[0]["transactionId"] == transaction_id_2
+ @pytest.mark.skip("transition to new metrics summaries processor in snuba")
def test_get_metric_spans_with_latest_release(self):
mri = "g:custom/page_load@millisecond"
@@ -563,6 +566,7 @@ def test_get_metric_spans_with_latest_release_not_found(self):
status_code=404,
)
+ @pytest.mark.skip("transition to new metrics summaries processor in snuba")
def test_get_metric_spans_with_bounds(self):
mri = "g:custom/page_load@millisecond"
|
908f43a327bb12aa8741d18d16af3cfe313a0192
|
2024-09-27 23:52:11
|
Evan Purkhiser
|
feat(rr6): Run frontend test suite using react-router 6 (#76471)
| false
|
Run frontend test suite using react-router 6 (#76471)
|
feat
|
diff --git a/tests/js/setup.ts b/tests/js/setup.ts
index eab46bfcc0d656..2571b636dfa210 100644
--- a/tests/js/setup.ts
+++ b/tests/js/setup.ts
@@ -16,6 +16,8 @@ import {DEFAULT_LOCALE_DATA, setLocale} from 'sentry/locale';
import ConfigStore from 'sentry/stores/configStore';
import * as performanceForSentry from 'sentry/utils/performanceForSentry';
+window.__SENTRY_USING_REACT_ROUTER_SIX = true;
+
/**
* Set locale to English
*/
|
6ca5a307b96dcec3246b05660eb5924e48e15f87
|
2023-03-15 02:43:45
|
Alberto Leal
|
chore(hybrid-cloud): Update organization mapping tests (#45788)
| false
|
Update organization mapping tests (#45788)
|
chore
|
diff --git a/tests/sentry/hybrid_cloud/test_organizationmapping.py b/tests/sentry/hybrid_cloud/test_organizationmapping.py
index c0a678ced67a82..56fc5eae5a3f29 100644
--- a/tests/sentry/hybrid_cloud/test_organizationmapping.py
+++ b/tests/sentry/hybrid_cloud/test_organizationmapping.py
@@ -22,13 +22,15 @@ def test_create(self):
}
rpc_org_mapping = organization_mapping_service.create(**fields)
org_mapping = OrganizationMapping.objects.get(organization_id=self.organization.id)
-
- assert rpc_org_mapping.organization_id == self.organization.id
- assert rpc_org_mapping.verified is False
- assert rpc_org_mapping.slug == fields["slug"]
- assert rpc_org_mapping.region_name == fields["region_name"]
+ assert org_mapping.idempotency_key == ""
+ assert (
+ rpc_org_mapping.organization_id == org_mapping.organization_id == self.organization.id
+ )
+ assert rpc_org_mapping.verified is org_mapping.verified is False
+ assert rpc_org_mapping.slug == org_mapping.slug == fields["slug"]
+ assert rpc_org_mapping.region_name == org_mapping.region_name == fields["region_name"]
assert rpc_org_mapping.date_created == org_mapping.date_created
- assert rpc_org_mapping.name == fields["name"]
+ assert rpc_org_mapping.name == org_mapping.name == fields["name"]
def test_idempotency_key(self):
data = {
@@ -44,7 +46,10 @@ def test_idempotency_key(self):
)
assert not OrganizationMapping.objects.filter(organization_id=self.organization.id).exists()
- assert OrganizationMapping.objects.filter(organization_id=next_organization_id)
+ org_mapping = OrganizationMapping.objects.filter(organization_id=next_organization_id)
+ assert org_mapping
+ org_mapping = org_mapping.first()
+ assert org_mapping.idempotency_key == data["idempotency_key"]
assert rpc_org_mapping.organization_id == next_organization_id
assert rpc_org_mapping.region_name == "us"
|
df35bd78031a73b261873a953aea226b08c9342a
|
2019-03-27 23:18:11
|
Lyn Nagara
|
feat(saved-search): Add components to save current search (#12534)
| false
|
Add components to save current search (#12534)
|
feat
|
diff --git a/src/sentry/static/sentry/app/views/stream/filters.jsx b/src/sentry/static/sentry/app/views/stream/filters.jsx
index c0055b5c60a3f4..1387f412125e49 100644
--- a/src/sentry/static/sentry/app/views/stream/filters.jsx
+++ b/src/sentry/static/sentry/app/views/stream/filters.jsx
@@ -93,6 +93,7 @@ class StreamFilters extends React.Component {
savedSearchList={savedSearchList}
onSavedSearchSelect={onSavedSearchSelect}
onSavedSearchDelete={onSavedSearchDelete}
+ query={query}
queryCount={queryCount}
queryMaxCount={queryMaxCount}
/>
diff --git a/src/sentry/static/sentry/app/views/stream/organizationSavedSearchSelector.jsx b/src/sentry/static/sentry/app/views/stream/organizationSavedSearchSelector.jsx
index 194ae506273ada..3cdd00b9d4ea6f 100644
--- a/src/sentry/static/sentry/app/views/stream/organizationSavedSearchSelector.jsx
+++ b/src/sentry/static/sentry/app/views/stream/organizationSavedSearchSelector.jsx
@@ -1,6 +1,7 @@
import React from 'react';
import PropTypes from 'prop-types';
import styled from 'react-emotion';
+import Modal from 'react-bootstrap/lib/Modal';
import {t} from 'app/locale';
import Access from 'app/components/acl/access';
@@ -11,7 +12,9 @@ import DropdownLink from 'app/components/dropdownLink';
import QueryCount from 'app/components/queryCount';
import InlineSvg from 'app/components/inlineSvg';
import SentryTypes from 'app/sentryTypes';
+import {TextField} from 'app/components/forms';
import space from 'app/styles/space';
+import withApi from 'app/utils/withApi';
export default class OrganizationSavedSearchSelector extends React.Component {
static propTypes = {
@@ -19,7 +22,7 @@ export default class OrganizationSavedSearchSelector extends React.Component {
savedSearchList: PropTypes.array.isRequired,
onSavedSearchSelect: PropTypes.func.isRequired,
onSavedSearchDelete: PropTypes.func.isRequired,
- query: PropTypes.string,
+ query: PropTypes.string.isRequired,
queryCount: PropTypes.number,
queryMaxCount: PropTypes.number,
searchId: PropTypes.string,
@@ -79,7 +82,7 @@ export default class OrganizationSavedSearchSelector extends React.Component {
}
render() {
- const {queryCount, queryMaxCount} = this.props;
+ const {organization, query, queryCount, queryMaxCount} = this.props;
return (
<Container>
@@ -92,12 +95,115 @@ export default class OrganizationSavedSearchSelector extends React.Component {
}
>
{this.renderList()}
+ <Access
+ organization={organization}
+ access={['org:write']}
+ renderNoAccessMessage={false}
+ >
+ <StyledMenuItem divider={true} />
+ <ButtonBar>
+ <SaveSearchButton query={query} organization={organization} />
+ </ButtonBar>
+ </Access>
</StyledDropdownLink>
</Container>
);
}
}
+const SaveSearchButton = withApi(
+ class SaveSearchButton extends React.Component {
+ static propTypes = {
+ // api: PropTypes.object.isRequired,
+ query: PropTypes.string.isRequired,
+ // organization: SentryTypes.Organization.isRequired,
+ };
+
+ constructor(props) {
+ super(props);
+ this.state = {
+ isModalOpen: false,
+ isSaving: false,
+ query: props.query,
+ name: '',
+ };
+ }
+
+ onSubmit = e => {
+ e.preventDefault();
+
+ // TODO: implement saving
+ };
+
+ onToggle = () => {
+ this.setState({
+ isModalOpen: !this.state.isModalOpen,
+ });
+ };
+
+ handleChangeName = val => {
+ this.setState({name: val});
+ };
+
+ handleChangeQuery = val => {
+ this.setState({query: val});
+ };
+
+ render() {
+ const {isSaving, isModalOpen} = this.state;
+
+ return (
+ <React.Fragment>
+ <Button size="xsmall" onClick={this.onToggle}>
+ {t('Save Current Search')}
+ </Button>
+ <Modal show={isModalOpen} animation={false} onHide={this.onToggle}>
+ <form onSubmit={this.onSubmit}>
+ <div className="modal-header">
+ <h4>{t('Save Current Search')}</h4>
+ </div>
+
+ <div className="modal-body">
+ <p>{t('All team members will now have access to this search.')}</p>
+ <TextField
+ key="name"
+ name="name"
+ label={t('Name')}
+ placeholder="e.g. My Search Results"
+ required={true}
+ onChange={this.handleChangeName}
+ />
+ <TextField
+ key="query"
+ name="query"
+ label={t('Query')}
+ value={this.props.query}
+ required={true}
+ onChange={this.handleChangeQuery}
+ />
+ </div>
+ <div className="modal-footer">
+ <Button
+ priority="default"
+ size="small"
+ disabled={isSaving}
+ onClick={this.onToggle}
+ style={{marginRight: space(1)}}
+ >
+ {t('Cancel')}
+ </Button>
+ <Button priority="primary" size="small" disabled={isSaving}>
+ {t('Save')}
+ </Button>
+ </div>
+ </form>
+ </Modal>
+ </React.Fragment>
+ );
+ }
+ }
+);
+
const Container = styled.div`
& .dropdown-menu {
max-width: 350px;
@@ -176,3 +282,15 @@ const EmptyItem = styled.li`
padding: 8px 10px 5px;
font-style: italic;
`;
+
+const ButtonBar = styled.li`
+ padding: ${space(0.5)} ${space(1)};
+ display: flex;
+ justify-content: space-between;
+
+ & a {
+ /* need to override .dropdown-menu li a in shared-components.less */
+ padding: 0 !important;
+ line-height: 1 !important;
+ }
+`;
diff --git a/tests/js/spec/views/stream/organizationSavedSearchSelector.spec.jsx b/tests/js/spec/views/stream/organizationSavedSearchSelector.spec.jsx
index 5e30394b18a08f..3d8867b5305ee2 100644
--- a/tests/js/spec/views/stream/organizationSavedSearchSelector.spec.jsx
+++ b/tests/js/spec/views/stream/organizationSavedSearchSelector.spec.jsx
@@ -6,7 +6,7 @@ import OrganizationSavedSearchSelector from 'app/views/stream/organizationSavedS
describe('OrganizationSavedSearchSelector', function() {
let wrapper, onSelect, onDelete, organization, savedSearchList;
beforeEach(function() {
- organization = TestStubs.Organization();
+ organization = TestStubs.Organization({access: ['org:write']});
onSelect = jest.fn();
onDelete = jest.fn();
savedSearchList = [
@@ -31,6 +31,7 @@ describe('OrganizationSavedSearchSelector', function() {
savedSearchList={savedSearchList}
onSavedSearchSelect={onSelect}
onSavedSearchDelete={onDelete}
+ query={'is:unresolved assigned:[email protected]'}
/>,
TestStubs.routerContext()
);
@@ -120,4 +121,27 @@ describe('OrganizationSavedSearchSelector', function() {
expect(onDelete).toHaveBeenCalledWith(savedSearchList[1]);
});
});
+
+ describe('saves a search', function() {
+ it('clicking save search opens modal', function() {
+ wrapper.find('DropdownLink').simulate('click');
+ expect(wrapper.find('ModalDialog')).toHaveLength(0);
+ wrapper
+ .find('button')
+ .at(0)
+ .simulate('click');
+
+ expect(wrapper.find('ModalDialog')).toHaveLength(1);
+ });
+
+ it('hides save search button if no access', function() {
+ const orgWithoutAccess = TestStubs.Organization({access: ['org:read']});
+
+ wrapper.setProps({organization: orgWithoutAccess});
+
+ const button = wrapper.find('button');
+
+ expect(button).toHaveLength(0);
+ });
+ });
});
|
215b5f9c51f4417f6245c72ccca8535b67355339
|
2021-04-01 03:44:21
|
MeredithAnya
|
ref(azure): Fix SENTRY-NT8 (#24677)
| false
|
Fix SENTRY-NT8 (#24677)
|
ref
|
diff --git a/src/sentry/integrations/vsts/webhooks.py b/src/sentry/integrations/vsts/webhooks.py
index 08ebd8ea89e99b..3dbe5cdc20c8cc 100644
--- a/src/sentry/integrations/vsts/webhooks.py
+++ b/src/sentry/integrations/vsts/webhooks.py
@@ -53,6 +53,7 @@ def post(self, request, *args, **kwargs):
"vsts.integration-in-webhook-payload-does-not-exist",
extra={"external_id": external_id, "event_type": event_type},
)
+ return self.respond({"detail": "Integration does not exist."}, status=400)
try:
self.check_webhook_secret(request, integration)
|
6170dae939f6e995b04594f0f44eebb9ede67981
|
2018-10-30 00:34:44
|
Jess MacQueen
|
feat(ui): Add ability to render 400 error messages to AsyncComponent
| false
|
Add ability to render 400 error messages to AsyncComponent
|
feat
|
diff --git a/src/sentry/static/sentry/app/components/asyncComponent.jsx b/src/sentry/static/sentry/app/components/asyncComponent.jsx
index fc948bbb14e8b8..26d2d654d666c9 100644
--- a/src/sentry/static/sentry/app/components/asyncComponent.jsx
+++ b/src/sentry/static/sentry/app/components/asyncComponent.jsx
@@ -50,6 +50,9 @@ export default class AsyncComponent extends React.Component {
// eslint-disable-next-line react/sort-comp
shouldReloadOnVisible = false;
+ // should `renderError` render the `detail` attribute of a 400 error
+ shouldRenderBadRequests = false;
+
constructor(props, context) {
super(props, context);
@@ -165,7 +168,6 @@ export default class AsyncComponent extends React.Component {
if (options.allowError && options.allowError(error)) {
error = null;
}
-
this.handleError(error, [stateKey, endpoint, params, options]);
},
});
@@ -301,6 +303,19 @@ export default class AsyncComponent extends React.Component {
return <PermissionDenied />;
}
+ if (this.shouldRenderBadRequests) {
+ let badRequests = Object.values(this.state.errors)
+ .filter(
+ resp =>
+ resp && resp.status === 400 && resp.responseJSON && resp.responseJSON.detail
+ )
+ .map(resp => resp.responseJSON.detail);
+
+ if (badRequests.length) {
+ return <LoadingError message={badRequests.join('\n')} />;
+ }
+ }
+
return (
<RouteError
error={error}
diff --git a/src/sentry/static/sentry/app/components/group/externalIssueActions.jsx b/src/sentry/static/sentry/app/components/group/externalIssueActions.jsx
index f3dff66c08d4f4..90b1ce642c50e3 100644
--- a/src/sentry/static/sentry/app/components/group/externalIssueActions.jsx
+++ b/src/sentry/static/sentry/app/components/group/externalIssueActions.jsx
@@ -36,6 +36,8 @@ class ExternalIssueForm extends AsyncComponent {
onSubmitSuccess: PropTypes.func.isRequired,
};
+ shouldRenderBadRequests = true;
+
getEndpoints() {
let {action, group, integration} = this.props;
return [
diff --git a/tests/js/setup.js b/tests/js/setup.js
index e68814efb3f487..8fc00d9d9786c2 100644
--- a/tests/js/setup.js
+++ b/tests/js/setup.js
@@ -101,6 +101,8 @@ jest.mock('echarts-for-react/lib/core', () => {
});
jest.mock('app/utils/sdk', () => ({
+ captureBreadcrumb: jest.fn(),
+ addBreadcrumb: jest.fn(),
captureMessage: jest.fn(),
captureException: jest.fn(),
showReportDialog: jest.fn(),
diff --git a/tests/js/spec/components/asyncComponent.spec.jsx b/tests/js/spec/components/asyncComponent.spec.jsx
new file mode 100644
index 00000000000000..4b0ae9d9a8864f
--- /dev/null
+++ b/tests/js/spec/components/asyncComponent.spec.jsx
@@ -0,0 +1,58 @@
+import React from 'react';
+import {mount, shallow} from 'enzyme';
+import {Client} from 'app/api';
+
+import AsyncComponent from 'app/components/asyncComponent';
+
+describe('AsyncComponent', function() {
+ class TestAsyncComponent extends AsyncComponent {
+ shouldRenderBadRequests = true;
+
+ constructor(props) {
+ super(props);
+ this.state = {};
+ }
+
+ getEndpoints() {
+ return [['data', '/some/path/to/something/']];
+ }
+
+ renderBody() {
+ return <div>{this.state.data.message}</div>;
+ }
+ }
+
+ it('renders on successful request', function() {
+ Client.clearMockResponses();
+ Client.addMockResponse({
+ url: '/some/path/to/something/',
+ method: 'GET',
+ body: {
+ message: 'hi',
+ },
+ });
+ let wrapper = shallow(<TestAsyncComponent />);
+ expect(wrapper.find('div')).toHaveLength(1);
+ expect(wrapper.find('div').text()).toEqual('hi');
+ });
+
+ it('renders error message', function() {
+ Client.clearMockResponses();
+ Client.addMockResponse({
+ url: '/some/path/to/something/',
+ method: 'GET',
+ body: {
+ detail: 'oops there was a problem',
+ },
+ statusCode: 400,
+ });
+ let wrapper = mount(<TestAsyncComponent />);
+ expect(wrapper.find('LoadingError')).toHaveLength(1);
+ expect(
+ wrapper
+ .find('LoadingError')
+ .find('p')
+ .text()
+ ).toEqual('oops there was a problem');
+ });
+});
|
1eb9cb4fe1070bfc1008b670ae1886af8debed09
|
2020-09-11 20:34:44
|
David Wang
|
ref(alert): Add helper text and change styles slightly #20721
| false
|
Add helper text and change styles slightly #20721
|
ref
|
diff --git a/src/sentry/rules/conditions/event_attribute.py b/src/sentry/rules/conditions/event_attribute.py
index d0dd0334e3a9cd..ffa28b6c113a34 100644
--- a/src/sentry/rules/conditions/event_attribute.py
+++ b/src/sentry/rules/conditions/event_attribute.py
@@ -75,7 +75,7 @@ class EventAttributeCondition(EventCondition):
# TODO(dcramer): add support for stacktrace.vars.[name]
form_cls = EventAttributeForm
- label = u"An event's {attribute} value {match} {value}"
+ label = u"The event's {attribute} value {match} {value}"
form_fields = {
"attribute": {
diff --git a/src/sentry/rules/conditions/every_event.py b/src/sentry/rules/conditions/every_event.py
index e294b4c94d84eb..c048b5c95d4556 100644
--- a/src/sentry/rules/conditions/every_event.py
+++ b/src/sentry/rules/conditions/every_event.py
@@ -4,7 +4,7 @@
class EveryEventCondition(EventCondition):
- label = "An event occurs"
+ label = "The event occurs"
def passes(self, event, state):
return True
diff --git a/src/sentry/rules/conditions/level.py b/src/sentry/rules/conditions/level.py
index ff094c1eb82c93..3f3a0ddd808601 100644
--- a/src/sentry/rules/conditions/level.py
+++ b/src/sentry/rules/conditions/level.py
@@ -34,7 +34,7 @@ class LevelEventForm(forms.Form):
class LevelCondition(EventCondition):
form_cls = LevelEventForm
- label = "An event's level is {match} {level}"
+ label = "The event's level is {match} {level}"
form_fields = {
"level": {"type": "choice", "choices": LEVEL_CHOICES.items()},
"match": {"type": "choice", "choices": MATCH_CHOICES.items()},
diff --git a/src/sentry/rules/conditions/tagged_event.py b/src/sentry/rules/conditions/tagged_event.py
index 5944917887fad1..b899d10473afe2 100644
--- a/src/sentry/rules/conditions/tagged_event.py
+++ b/src/sentry/rules/conditions/tagged_event.py
@@ -49,7 +49,7 @@ def clean(self):
class TaggedEventCondition(EventCondition):
form_cls = TaggedEventForm
- label = u"An event's tags match {key} {match} {value}"
+ label = u"The event's tags match {key} {match} {value}"
form_fields = {
"key": {"type": "string", "placeholder": "key"},
diff --git a/src/sentry/static/sentry/app/views/settings/projectAlerts/issueEditor/index.tsx b/src/sentry/static/sentry/app/views/settings/projectAlerts/issueEditor/index.tsx
index 0ee9a5eb019c7c..38de0809117360 100644
--- a/src/sentry/static/sentry/app/views/settings/projectAlerts/issueEditor/index.tsx
+++ b/src/sentry/static/sentry/app/views/settings/projectAlerts/issueEditor/index.tsx
@@ -475,7 +475,14 @@ class IssueRuleEditor extends AsyncView<Props, State> {
</Panel>
<Panel>
- <PanelHeader>{t('Alert Conditions')}</PanelHeader>
+ <StyledPanelHeader>
+ {t('Alert Conditions')}
+ <PanelHelpText>
+ {t(
+ 'Conditions are evaluated every time an event is captured by Sentry.'
+ )}
+ </PanelHelpText>
+ </StyledPanelHeader>
<PanelBody>
{detailedError && (
<PanelAlert type="error">
@@ -693,6 +700,19 @@ const StyledForm = styled(Form)`
position: relative;
`;
+const StyledPanelHeader = styled(PanelHeader)`
+ flex-direction: column;
+ align-items: flex-start;
+`;
+
+const PanelHelpText = styled('div')`
+ color: ${p => p.theme.gray500};
+ font-size: 14px;
+ font-weight: normal;
+ text-transform: none;
+ margin-top: ${space(1)};
+`;
+
const StyledAlert = styled(Alert)`
margin-bottom: 0;
`;
@@ -724,7 +744,7 @@ const StepConnector = styled('div')`
`;
const StepLead = styled('div')`
- margin-bottom: ${space(2)};
+ margin-bottom: ${space(0.5)};
`;
const ChevronContainer = styled('div')`
@@ -735,7 +755,7 @@ const ChevronContainer = styled('div')`
const Badge = styled('span')`
display: inline-block;
- min-width: 51px;
+ min-width: 56px;
background-color: ${p => p.theme.purple400};
padding: 0 ${space(0.75)};
border-radius: ${p => p.theme.borderRadius};
@@ -743,7 +763,7 @@ const Badge = styled('span')`
text-transform: uppercase;
text-align: center;
font-size: ${p => p.theme.fontSizeMedium};
- font-weight: 500;
+ font-weight: 600;
line-height: 1.5;
`;
diff --git a/src/sentry/testutils/factories.py b/src/sentry/testutils/factories.py
index 5efea0aa1c2903..c174bd0b0d5a1a 100644
--- a/src/sentry/testutils/factories.py
+++ b/src/sentry/testutils/factories.py
@@ -325,7 +325,7 @@ def create_project_rule(project, action_data=None, condition_data=None):
},
{
"id": "sentry.rules.conditions.every_event.EveryEventCondition",
- "name": "An event occurs",
+ "name": "The event occurs",
},
]
return Rule.objects.create(
diff --git a/tests/acceptance/test_project_alert_settings.py b/tests/acceptance/test_project_alert_settings.py
index fc46d27e1bf501..15927275013dbd 100644
--- a/tests/acceptance/test_project_alert_settings.py
+++ b/tests/acceptance/test_project_alert_settings.py
@@ -31,7 +31,7 @@ def setUp(self):
},
{
"id": "sentry.rules.conditions.every_event.EveryEventCondition",
- "name": "An event occurs",
+ "name": "The event occurs",
},
]
diff --git a/tests/sentry/rules/conditions/test_event_attribute.py b/tests/sentry/rules/conditions/test_event_attribute.py
index ab8d467c3108bc..9b19b2bd98dbc9 100644
--- a/tests/sentry/rules/conditions/test_event_attribute.py
+++ b/tests/sentry/rules/conditions/test_event_attribute.py
@@ -46,7 +46,7 @@ def test_render_label(self):
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": u"\xc3", "value": u"\xc4"}
)
- assert rule.render_label() == u"An event's \xc3 value equals \xc4"
+ assert rule.render_label() == u"The event's \xc3 value equals \xc4"
def test_equals(self):
event = self.get_event()
diff --git a/tests/sentry/rules/conditions/test_level_event.py b/tests/sentry/rules/conditions/test_level_event.py
index 1d94cf290127ff..bffa1f0881695e 100644
--- a/tests/sentry/rules/conditions/test_level_event.py
+++ b/tests/sentry/rules/conditions/test_level_event.py
@@ -9,7 +9,7 @@ class LevelConditionTest(RuleTestCase):
def test_render_label(self):
rule = self.get_rule(data={"match": MatchType.EQUAL, "level": "30"})
- assert rule.render_label() == u"An event's level is equal to warning"
+ assert rule.render_label() == u"The event's level is equal to warning"
def test_equals(self):
event = self.store_event(data={"level": "info"}, project_id=self.project.id)
diff --git a/tests/sentry/rules/conditions/test_tagged_event.py b/tests/sentry/rules/conditions/test_tagged_event.py
index 2aff12dca15c10..f955ea21398e06 100644
--- a/tests/sentry/rules/conditions/test_tagged_event.py
+++ b/tests/sentry/rules/conditions/test_tagged_event.py
@@ -19,7 +19,7 @@ def get_event(self):
def test_render_label(self):
rule = self.get_rule(data={"match": MatchType.EQUAL, "key": u"\xc3", "value": u"\xc4"})
- assert rule.render_label() == u"An event's tags match \xc3 equals \xc4"
+ assert rule.render_label() == u"The event's tags match \xc3 equals \xc4"
def test_equals(self):
event = self.get_event()
|
726a5ec8d74e449c6f026c18ef09d0961b4ad5fb
|
2024-12-10 01:53:22
|
Andrew Liu
|
feat(feedback): suggest 'trace' filter in feedback index (#81870)
| false
|
suggest 'trace' filter in feedback index (#81870)
|
feat
|
diff --git a/static/app/utils/fields/index.ts b/static/app/utils/fields/index.ts
index f132702b693703..42b8df7dce5c45 100644
--- a/static/app/utils/fields/index.ts
+++ b/static/app/utils/fields/index.ts
@@ -2343,6 +2343,7 @@ export const FEEDBACK_FIELDS = [
FieldKey.SDK_NAME,
FieldKey.SDK_VERSION,
FieldKey.TIMESTAMP,
+ FieldKey.TRACE,
FieldKey.TRANSACTION,
FeedbackFieldKey.URL,
FieldKey.USER_EMAIL,
|
7c048986a6ac4956e4f4e131bbb89838ae083820
|
2023-06-08 04:01:18
|
Malachi Willey
|
fix(user-settings): Generate timezone offset labels dynamically to account for daylight savings (#50529)
| false
|
Generate timezone offset labels dynamically to account for daylight savings (#50529)
|
fix
|
diff --git a/static/app/data/timezones.tsx b/static/app/data/timezones.tsx
index 8e636ef9f4f45f..c79b4276b911e7 100644
--- a/static/app/data/timezones.tsx
+++ b/static/app/data/timezones.tsx
@@ -1,5 +1,6 @@
import styled from '@emotion/styled';
import groupBy from 'lodash/groupBy';
+import moment from 'moment-timezone';
import {SelectValue} from 'sentry/types';
@@ -18,454 +19,449 @@ type TimezoneGroup =
| 'Antarctica'
| 'Arctic';
-const timezones: [
- group: TimezoneGroup,
- offsetLabel: string,
- value: string,
- label: string
-][] = [
- ['Other', '+0', 'UTC', 'UTC'],
- ['Other', '+0', 'GMT', 'GMT'],
+const timezones: [group: TimezoneGroup, value: string, label: string][] = [
+ ['Other', 'UTC', 'UTC'],
+ ['Other', 'GMT', 'GMT'],
// Group US higher-ish since
- ['US/Canada', '-5', 'US/Eastern', 'Eastern'],
- ['US/Canada', '-6', 'US/Central', 'Central'],
- ['US/Canada', '-7', 'US/Arizona', 'Arizona'],
- ['US/Canada', '-7', 'US/Mountain', 'Mountain'],
- ['US/Canada', '-8', 'US/Pacific', 'Pacific'],
- ['US/Canada', '-9', 'US/Alaska', 'Alaska'],
- ['US/Canada', '-10', 'US/Hawaii', 'Hawaii'],
- ['US/Canada', '-3:30', 'Canada/Newfoundland', 'Newfoundland'],
- ['US/Canada', '-4', 'Canada/Atlantic', 'Atlantic'],
- ['US/Canada', '-5', 'Canada/Eastern', 'Canadian Eastern'],
- ['US/Canada', '-6', 'Canada/Central', 'Canadian Central'],
- ['US/Canada', '-7', 'Canada/Mountain', 'Canadian Mountain'],
- ['US/Canada', '-8', 'Canada/Pacific', 'Canadian Pacific'],
+ ['US/Canada', 'US/Eastern', 'Eastern'],
+ ['US/Canada', 'US/Central', 'Central'],
+ ['US/Canada', 'US/Arizona', 'Arizona'],
+ ['US/Canada', 'US/Mountain', 'Mountain'],
+ ['US/Canada', 'US/Pacific', 'Pacific'],
+ ['US/Canada', 'US/Alaska', 'Alaska'],
+ ['US/Canada', 'US/Hawaii', 'Hawaii'],
+ ['US/Canada', 'Canada/Newfoundland', 'Newfoundland'],
+ ['US/Canada', 'Canada/Atlantic', 'Atlantic'],
+ ['US/Canada', 'Canada/Eastern', 'Canadian Eastern'],
+ ['US/Canada', 'Canada/Central', 'Canadian Central'],
+ ['US/Canada', 'Canada/Mountain', 'Canadian Mountain'],
+ ['US/Canada', 'Canada/Pacific', 'Canadian Pacific'],
- ['America', '+0', 'America/Danmarkshavn', 'Danmarkshavn'],
- ['America', '-1', 'America/Scoresbysund', 'Scoresbysund'],
- ['America', '-2', 'America/Noronha', 'Noronha'],
- ['America', '-3', 'America/Araguaina', 'Araguaina'],
- ['America', '-3', 'America/Argentina/Buenos_Aires', 'Argentina / Buenos Aires'],
- ['America', '-3', 'America/Argentina/Catamarca', 'Argentina / Catamarca'],
- ['America', '-3', 'America/Argentina/Cordoba', 'Argentina / Cordoba'],
- ['America', '-3', 'America/Argentina/Jujuy', 'Argentina / Jujuy'],
- ['America', '-3', 'America/Argentina/La_Rioja', 'Argentina / La Rioja'],
- ['America', '-3', 'America/Argentina/Mendoza', 'Argentina / Mendoza'],
- ['America', '-3', 'America/Argentina/Rio_Gallegos', 'Argentina / Rio Gallegos'],
- ['America', '-3', 'America/Argentina/Salta', 'Argentina / Salta'],
- ['America', '-3', 'America/Argentina/San_Juan', 'Argentina / San Juan'],
- ['America', '-3', 'America/Argentina/San_Luis', 'Argentina / San Luis'],
- ['America', '-3', 'America/Argentina/Tucuman', 'Argentina / Tucuman'],
- ['America', '-3', 'America/Argentina/Ushuaia', 'Argentina / Ushuaia'],
- ['America', '-3', 'America/Asuncion', 'Asuncion'],
- ['America', '-3', 'America/Bahia', 'Bahia'],
- ['America', '-3', 'America/Belem', 'Belem'],
- ['America', '-3', 'America/Campo_Grande', 'Campo Grande'],
- ['America', '-3', 'America/Cayenne', 'Cayenne'],
- ['America', '-3', 'America/Cuiaba', 'Cuiaba'],
- ['America', '-3', 'America/Fortaleza', 'Fortaleza'],
- ['America', '-3', 'America/Godthab', 'Godthab'],
- ['America', '-3', 'America/Maceio', 'Maceio'],
- ['America', '-3', 'America/Miquelon', 'Miquelon'],
- ['America', '-3', 'America/Montevideo', 'Montevideo'],
- ['America', '-3', 'America/Paramaribo', 'Paramaribo'],
- ['America', '-3', 'America/Recife', 'Recife'],
- ['America', '-3', 'America/Santarem', 'Santarem'],
- ['America', '-3', 'America/Santiago', 'Santiago'],
- ['America', '-3', 'America/Sao_Paulo', 'Sao Paulo'],
- ['America', '-3:30', 'America/St_Johns', 'St Johns'],
- ['America', '-4', 'America/Anguilla', 'Anguilla'],
- ['America', '-4', 'America/Antigua', 'Antigua'],
- ['America', '-4', 'America/Aruba', 'Aruba'],
- ['America', '-4', 'America/Barbados', 'Barbados'],
- ['America', '-4', 'America/Blanc-Sablon', 'Blanc-Sablon'],
- ['America', '-4', 'America/Boa_Vista', 'Boa Vista'],
- ['America', '-4', 'America/Caracas', 'Caracas'],
- ['America', '-4', 'America/Curacao', 'Curacao'],
- ['America', '-4', 'America/Dominica', 'Dominica'],
- ['America', '-4', 'America/Glace_Bay', 'Glace Bay'],
- ['America', '-4', 'America/Goose_Bay', 'Goose Bay'],
- ['America', '-4', 'America/Grenada', 'Grenada'],
- ['America', '-4', 'America/Guadeloupe', 'Guadeloupe'],
- ['America', '-4', 'America/Guyana', 'Guyana'],
- ['America', '-4', 'America/Halifax', 'Halifax'],
- ['America', '-4', 'America/Kralendijk', 'Kralendijk'],
- ['America', '-4', 'America/La_Paz', 'La Paz'],
- ['America', '-4', 'America/Lower_Princes', 'Lower Princes'],
- ['America', '-4', 'America/Manaus', 'Manaus'],
- ['America', '-4', 'America/Marigot', 'Marigot'],
- ['America', '-4', 'America/Martinique', 'Martinique'],
- ['America', '-4', 'America/Moncton', 'Moncton'],
- ['America', '-4', 'America/Montserrat', 'Montserrat'],
- ['America', '-4', 'America/Port_of_Spain', 'Port of Spain'],
- ['America', '-4', 'America/Porto_Velho', 'Porto Velho'],
- ['America', '-4', 'America/Puerto_Rico', 'Puerto Rico'],
- ['America', '-4', 'America/Santo_Domingo', 'Santo Domingo'],
- ['America', '-4', 'America/St_Barthelemy', 'St Barthelemy'],
- ['America', '-4', 'America/St_Kitts', 'St Kitts'],
- ['America', '-4', 'America/St_Lucia', 'St Lucia'],
- ['America', '-4', 'America/St_Thomas', 'St Thomas'],
- ['America', '-4', 'America/St_Vincent', 'St Vincent'],
- ['America', '-4', 'America/Thule', 'Thule'],
- ['America', '-4', 'America/Tortola', 'Tortola'],
- ['America', '-5', 'America/Atikokan', 'Atikokan'],
- ['America', '-5', 'America/Bogota', 'Bogota'],
- ['America', '-5', 'America/Cancun', 'Cancun'],
- ['America', '-5', 'America/Cayman', 'Cayman'],
- ['America', '-5', 'America/Detroit', 'Detroit'],
- ['America', '-5', 'America/Eirunepe', 'Eirunepe'],
- ['America', '-5', 'America/Grand_Turk', 'Grand Turk'],
- ['America', '-5', 'America/Guayaquil', 'Guayaquil'],
- ['America', '-5', 'America/Havana', 'Havana'],
- ['America', '-5', 'America/Indiana/Indianapolis', 'Indiana / Indianapolis'],
- ['America', '-5', 'America/Indiana/Marengo', 'Indiana / Marengo'],
- ['America', '-5', 'America/Indiana/Petersburg', 'Indiana / Petersburg'],
- ['America', '-5', 'America/Indiana/Vevay', 'Indiana / Vevay'],
- ['America', '-5', 'America/Indiana/Vincennes', 'Indiana / Vincennes'],
- ['America', '-5', 'America/Indiana/Winamac', 'Indiana / Winamac'],
- ['America', '-5', 'America/Iqaluit', 'Iqaluit'],
- ['America', '-5', 'America/Jamaica', 'Jamaica'],
- ['America', '-5', 'America/Kentucky/Louisville', 'Kentucky / Louisville'],
- ['America', '-5', 'America/Kentucky/Monticello', 'Kentucky / Monticello'],
- ['America', '-5', 'America/Lima', 'Lima'],
- ['America', '-5', 'America/Nassau', 'Nassau'],
- ['America', '-5', 'America/New_York', 'New York'],
- ['America', '-5', 'America/Nipigon', 'Nipigon'],
- ['America', '-5', 'America/Panama', 'Panama'],
- ['America', '-5', 'America/Pangnirtung', 'Pangnirtung'],
- ['America', '-5', 'America/Port-au-Prince', 'Port-au-Prince'],
- ['America', '-5', 'America/Rio_Branco', 'Rio Branco'],
- ['America', '-5', 'America/Thunder_Bay', 'Thunder Bay'],
- ['America', '-5', 'America/Toronto', 'Toronto'],
- ['America', '-6', 'America/Bahia_Banderas', 'Bahia Banderas'],
- ['America', '-6', 'America/Belize', 'Belize'],
- ['America', '-6', 'America/Chicago', 'Chicago'],
- ['America', '-6', 'America/Costa_Rica', 'Costa Rica'],
- ['America', '-6', 'America/El_Salvador', 'El Salvador'],
- ['America', '-6', 'America/Guatemala', 'Guatemala'],
- ['America', '-6', 'America/Indiana/Knox', 'Indiana / Knox'],
- ['America', '-6', 'America/Indiana/Tell_City', 'Indiana / Tell City'],
- ['America', '-6', 'America/Managua', 'Managua'],
- ['America', '-6', 'America/Matamoros', 'Matamoros'],
- ['America', '-6', 'America/Menominee', 'Menominee'],
- ['America', '-6', 'America/Merida', 'Merida'],
- ['America', '-6', 'America/Mexico_City', 'Mexico City'],
- ['America', '-6', 'America/Monterrey', 'Monterrey'],
- ['America', '-6', 'America/North_Dakota/Beulah', 'North Dakota / Beulah'],
- ['America', '-6', 'America/North_Dakota/Center', 'North Dakota / Center'],
- ['America', '-6', 'America/North_Dakota/New_Salem', 'North Dakota / New Salem'],
- ['America', '-6', 'America/Rainy_River', 'Rainy River'],
- ['America', '-6', 'America/Rankin_Inlet', 'Rankin Inlet'],
- ['America', '-6', 'America/Regina', 'Regina'],
- ['America', '-6', 'America/Resolute', 'Resolute'],
- ['America', '-6', 'America/Swift_Current', 'Swift Current'],
- ['America', '-6', 'America/Tegucigalpa', 'Tegucigalpa'],
- ['America', '-6', 'America/Winnipeg', 'Winnipeg'],
- ['America', '-7', 'America/Boise', 'Boise'],
- ['America', '-7', 'America/Cambridge_Bay', 'Cambridge Bay'],
- ['America', '-7', 'America/Chihuahua', 'Chihuahua'],
- ['America', '-7', 'America/Creston', 'Creston'],
- ['America', '-7', 'America/Dawson_Creek', 'Dawson Creek'],
- ['America', '-7', 'America/Denver', 'Denver'],
- ['America', '-7', 'America/Edmonton', 'Edmonton'],
- ['America', '-7', 'America/Fort_Nelson', 'Fort Nelson'],
- ['America', '-7', 'America/Hermosillo', 'Hermosillo'],
- ['America', '-7', 'America/Inuvik', 'Inuvik'],
- ['America', '-7', 'America/Mazatlan', 'Mazatlan'],
- ['America', '-7', 'America/Ojinaga', 'Ojinaga'],
- ['America', '-7', 'America/Phoenix', 'Phoenix'],
- ['America', '-7', 'America/Yellowknife', 'Yellowknife'],
- ['America', '-8', 'America/Dawson', 'Dawson'],
- ['America', '-8', 'America/Los_Angeles', 'Los Angeles'],
- ['America', '-8', 'America/Tijuana', 'Tijuana'],
- ['America', '-8', 'America/Vancouver', 'Vancouver'],
- ['America', '-8', 'America/Whitehorse', 'Whitehorse'],
- ['America', '-9', 'America/Anchorage', 'Anchorage'],
- ['America', '-9', 'America/Juneau', 'Juneau'],
- ['America', '-9', 'America/Metlakatla', 'Metlakatla'],
- ['America', '-9', 'America/Nome', 'Nome'],
- ['America', '-9', 'America/Sitka', 'Sitka'],
- ['America', '-9', 'America/Yakutat', 'Yakutat'],
- ['America', '-10', 'America/Adak', 'Adak'],
+ ['America', 'America/Danmarkshavn', 'Danmarkshavn'],
+ ['America', 'America/Scoresbysund', 'Scoresbysund'],
+ ['America', 'America/Noronha', 'Noronha'],
+ ['America', 'America/Araguaina', 'Araguaina'],
+ ['America', 'America/Argentina/Buenos_Aires', 'Argentina / Buenos Aires'],
+ ['America', 'America/Argentina/Catamarca', 'Argentina / Catamarca'],
+ ['America', 'America/Argentina/Cordoba', 'Argentina / Cordoba'],
+ ['America', 'America/Argentina/Jujuy', 'Argentina / Jujuy'],
+ ['America', 'America/Argentina/La_Rioja', 'Argentina / La Rioja'],
+ ['America', 'America/Argentina/Mendoza', 'Argentina / Mendoza'],
+ ['America', 'America/Argentina/Rio_Gallegos', 'Argentina / Rio Gallegos'],
+ ['America', 'America/Argentina/Salta', 'Argentina / Salta'],
+ ['America', 'America/Argentina/San_Juan', 'Argentina / San Juan'],
+ ['America', 'America/Argentina/San_Luis', 'Argentina / San Luis'],
+ ['America', 'America/Argentina/Tucuman', 'Argentina / Tucuman'],
+ ['America', 'America/Argentina/Ushuaia', 'Argentina / Ushuaia'],
+ ['America', 'America/Asuncion', 'Asuncion'],
+ ['America', 'America/Bahia', 'Bahia'],
+ ['America', 'America/Belem', 'Belem'],
+ ['America', 'America/Campo_Grande', 'Campo Grande'],
+ ['America', 'America/Cayenne', 'Cayenne'],
+ ['America', 'America/Cuiaba', 'Cuiaba'],
+ ['America', 'America/Fortaleza', 'Fortaleza'],
+ ['America', 'America/Godthab', 'Godthab'],
+ ['America', 'America/Maceio', 'Maceio'],
+ ['America', 'America/Miquelon', 'Miquelon'],
+ ['America', 'America/Montevideo', 'Montevideo'],
+ ['America', 'America/Paramaribo', 'Paramaribo'],
+ ['America', 'America/Recife', 'Recife'],
+ ['America', 'America/Santarem', 'Santarem'],
+ ['America', 'America/Santiago', 'Santiago'],
+ ['America', 'America/Sao_Paulo', 'Sao Paulo'],
+ ['America', 'America/St_Johns', 'St Johns'],
+ ['America', 'America/Anguilla', 'Anguilla'],
+ ['America', 'America/Antigua', 'Antigua'],
+ ['America', 'America/Aruba', 'Aruba'],
+ ['America', 'America/Barbados', 'Barbados'],
+ ['America', 'America/Blanc-Sablon', 'Blanc-Sablon'],
+ ['America', 'America/Boa_Vista', 'Boa Vista'],
+ ['America', 'America/Caracas', 'Caracas'],
+ ['America', 'America/Curacao', 'Curacao'],
+ ['America', 'America/Dominica', 'Dominica'],
+ ['America', 'America/Glace_Bay', 'Glace Bay'],
+ ['America', 'America/Goose_Bay', 'Goose Bay'],
+ ['America', 'America/Grenada', 'Grenada'],
+ ['America', 'America/Guadeloupe', 'Guadeloupe'],
+ ['America', 'America/Guyana', 'Guyana'],
+ ['America', 'America/Halifax', 'Halifax'],
+ ['America', 'America/Kralendijk', 'Kralendijk'],
+ ['America', 'America/La_Paz', 'La Paz'],
+ ['America', 'America/Lower_Princes', 'Lower Princes'],
+ ['America', 'America/Manaus', 'Manaus'],
+ ['America', 'America/Marigot', 'Marigot'],
+ ['America', 'America/Martinique', 'Martinique'],
+ ['America', 'America/Moncton', 'Moncton'],
+ ['America', 'America/Montserrat', 'Montserrat'],
+ ['America', 'America/Port_of_Spain', 'Port of Spain'],
+ ['America', 'America/Porto_Velho', 'Porto Velho'],
+ ['America', 'America/Puerto_Rico', 'Puerto Rico'],
+ ['America', 'America/Santo_Domingo', 'Santo Domingo'],
+ ['America', 'America/St_Barthelemy', 'St Barthelemy'],
+ ['America', 'America/St_Kitts', 'St Kitts'],
+ ['America', 'America/St_Lucia', 'St Lucia'],
+ ['America', 'America/St_Thomas', 'St Thomas'],
+ ['America', 'America/St_Vincent', 'St Vincent'],
+ ['America', 'America/Thule', 'Thule'],
+ ['America', 'America/Tortola', 'Tortola'],
+ ['America', 'America/Atikokan', 'Atikokan'],
+ ['America', 'America/Bogota', 'Bogota'],
+ ['America', 'America/Cancun', 'Cancun'],
+ ['America', 'America/Cayman', 'Cayman'],
+ ['America', 'America/Detroit', 'Detroit'],
+ ['America', 'America/Eirunepe', 'Eirunepe'],
+ ['America', 'America/Grand_Turk', 'Grand Turk'],
+ ['America', 'America/Guayaquil', 'Guayaquil'],
+ ['America', 'America/Havana', 'Havana'],
+ ['America', 'America/Indiana/Indianapolis', 'Indiana / Indianapolis'],
+ ['America', 'America/Indiana/Marengo', 'Indiana / Marengo'],
+ ['America', 'America/Indiana/Petersburg', 'Indiana / Petersburg'],
+ ['America', 'America/Indiana/Vevay', 'Indiana / Vevay'],
+ ['America', 'America/Indiana/Vincennes', 'Indiana / Vincennes'],
+ ['America', 'America/Indiana/Winamac', 'Indiana / Winamac'],
+ ['America', 'America/Iqaluit', 'Iqaluit'],
+ ['America', 'America/Jamaica', 'Jamaica'],
+ ['America', 'America/Kentucky/Louisville', 'Kentucky / Louisville'],
+ ['America', 'America/Kentucky/Monticello', 'Kentucky / Monticello'],
+ ['America', 'America/Lima', 'Lima'],
+ ['America', 'America/Nassau', 'Nassau'],
+ ['America', 'America/New_York', 'New York'],
+ ['America', 'America/Nipigon', 'Nipigon'],
+ ['America', 'America/Panama', 'Panama'],
+ ['America', 'America/Pangnirtung', 'Pangnirtung'],
+ ['America', 'America/Port-au-Prince', 'Port-au-Prince'],
+ ['America', 'America/Rio_Branco', 'Rio Branco'],
+ ['America', 'America/Thunder_Bay', 'Thunder Bay'],
+ ['America', 'America/Toronto', 'Toronto'],
+ ['America', 'America/Bahia_Banderas', 'Bahia Banderas'],
+ ['America', 'America/Belize', 'Belize'],
+ ['America', 'America/Chicago', 'Chicago'],
+ ['America', 'America/Costa_Rica', 'Costa Rica'],
+ ['America', 'America/El_Salvador', 'El Salvador'],
+ ['America', 'America/Guatemala', 'Guatemala'],
+ ['America', 'America/Indiana/Knox', 'Indiana / Knox'],
+ ['America', 'America/Indiana/Tell_City', 'Indiana / Tell City'],
+ ['America', 'America/Managua', 'Managua'],
+ ['America', 'America/Matamoros', 'Matamoros'],
+ ['America', 'America/Menominee', 'Menominee'],
+ ['America', 'America/Merida', 'Merida'],
+ ['America', 'America/Mexico_City', 'Mexico City'],
+ ['America', 'America/Monterrey', 'Monterrey'],
+ ['America', 'America/North_Dakota/Beulah', 'North Dakota / Beulah'],
+ ['America', 'America/North_Dakota/Center', 'North Dakota / Center'],
+ ['America', 'America/North_Dakota/New_Salem', 'North Dakota / New Salem'],
+ ['America', 'America/Rainy_River', 'Rainy River'],
+ ['America', 'America/Rankin_Inlet', 'Rankin Inlet'],
+ ['America', 'America/Regina', 'Regina'],
+ ['America', 'America/Resolute', 'Resolute'],
+ ['America', 'America/Swift_Current', 'Swift Current'],
+ ['America', 'America/Tegucigalpa', 'Tegucigalpa'],
+ ['America', 'America/Winnipeg', 'Winnipeg'],
+ ['America', 'America/Boise', 'Boise'],
+ ['America', 'America/Cambridge_Bay', 'Cambridge Bay'],
+ ['America', 'America/Chihuahua', 'Chihuahua'],
+ ['America', 'America/Creston', 'Creston'],
+ ['America', 'America/Dawson_Creek', 'Dawson Creek'],
+ ['America', 'America/Denver', 'Denver'],
+ ['America', 'America/Edmonton', 'Edmonton'],
+ ['America', 'America/Fort_Nelson', 'Fort Nelson'],
+ ['America', 'America/Hermosillo', 'Hermosillo'],
+ ['America', 'America/Inuvik', 'Inuvik'],
+ ['America', 'America/Mazatlan', 'Mazatlan'],
+ ['America', 'America/Ojinaga', 'Ojinaga'],
+ ['America', 'America/Phoenix', 'Phoenix'],
+ ['America', 'America/Yellowknife', 'Yellowknife'],
+ ['America', 'America/Dawson', 'Dawson'],
+ ['America', 'America/Los_Angeles', 'Los Angeles'],
+ ['America', 'America/Tijuana', 'Tijuana'],
+ ['America', 'America/Vancouver', 'Vancouver'],
+ ['America', 'America/Whitehorse', 'Whitehorse'],
+ ['America', 'America/Anchorage', 'Anchorage'],
+ ['America', 'America/Juneau', 'Juneau'],
+ ['America', 'America/Metlakatla', 'Metlakatla'],
+ ['America', 'America/Nome', 'Nome'],
+ ['America', 'America/Sitka', 'Sitka'],
+ ['America', 'America/Yakutat', 'Yakutat'],
+ ['America', 'America/Adak', 'Adak'],
- ['Europe', '+0', 'Europe/Dublin', 'Dublin'],
- ['Europe', '+0', 'Europe/Guernsey', 'Guernsey'],
- ['Europe', '+0', 'Europe/Isle_of_Man', 'Isle of Man'],
- ['Europe', '+0', 'Europe/Jersey', 'Jersey'],
- ['Europe', '+0', 'Europe/Lisbon', 'Lisbon'],
- ['Europe', '+0', 'Europe/London', 'London'],
- ['Europe', '+1', 'Europe/Amsterdam', 'Amsterdam'],
- ['Europe', '+1', 'Europe/Andorra', 'Andorra'],
- ['Europe', '+1', 'Europe/Belgrade', 'Belgrade'],
- ['Europe', '+1', 'Europe/Berlin', 'Berlin'],
- ['Europe', '+1', 'Europe/Bratislava', 'Bratislava'],
- ['Europe', '+1', 'Europe/Brussels', 'Brussels'],
- ['Europe', '+1', 'Europe/Budapest', 'Budapest'],
- ['Europe', '+1', 'Europe/Busingen', 'Busingen'],
- ['Europe', '+1', 'Europe/Copenhagen', 'Copenhagen'],
- ['Europe', '+1', 'Europe/Gibraltar', 'Gibraltar'],
- ['Europe', '+1', 'Europe/Ljubljana', 'Ljubljana'],
- ['Europe', '+1', 'Europe/Luxembourg', 'Luxembourg'],
- ['Europe', '+1', 'Europe/Madrid', 'Madrid'],
- ['Europe', '+1', 'Europe/Malta', 'Malta'],
- ['Europe', '+1', 'Europe/Monaco', 'Monaco'],
- ['Europe', '+1', 'Europe/Oslo', 'Oslo'],
- ['Europe', '+1', 'Europe/Paris', 'Paris'],
- ['Europe', '+1', 'Europe/Podgorica', 'Podgorica'],
- ['Europe', '+1', 'Europe/Prague', 'Prague'],
- ['Europe', '+1', 'Europe/Rome', 'Rome'],
- ['Europe', '+1', 'Europe/San_Marino', 'San Marino'],
- ['Europe', '+1', 'Europe/Sarajevo', 'Sarajevo'],
- ['Europe', '+1', 'Europe/Skopje', 'Skopje'],
- ['Europe', '+1', 'Europe/Stockholm', 'Stockholm'],
- ['Europe', '+1', 'Europe/Tirane', 'Tirane'],
- ['Europe', '+1', 'Europe/Vaduz', 'Vaduz'],
- ['Europe', '+1', 'Europe/Vatican', 'Vatican'],
- ['Europe', '+1', 'Europe/Vienna', 'Vienna'],
- ['Europe', '+1', 'Europe/Warsaw', 'Warsaw'],
- ['Europe', '+1', 'Europe/Zagreb', 'Zagreb'],
- ['Europe', '+1', 'Europe/Zurich', 'Zurich'],
- ['Europe', '+2', 'Europe/Athens', 'Athens'],
- ['Europe', '+2', 'Europe/Bucharest', 'Bucharest'],
- ['Europe', '+2', 'Europe/Chisinau', 'Chisinau'],
- ['Europe', '+2', 'Europe/Helsinki', 'Helsinki'],
- ['Europe', '+2', 'Europe/Kaliningrad', 'Kaliningrad'],
- ['Europe', '+2', 'Europe/Mariehamn', 'Mariehamn'],
- ['Europe', '+2', 'Europe/Riga', 'Riga'],
- ['Europe', '+2', 'Europe/Sofia', 'Sofia'],
- ['Europe', '+2', 'Europe/Tallinn', 'Tallinn'],
- ['Europe', '+2', 'Europe/Uzhgorod', 'Uzhgorod'],
- ['Europe', '+2', 'Europe/Vilnius', 'Vilnius'],
- ['Europe', '+2', 'Europe/Zaporozhye', 'Zaporozhye'],
- ['Europe', '+3', 'Europe/Istanbul', 'Istanbul'],
- ['Europe', '+3', 'Europe/Kiev', 'Kiev'],
- ['Europe', '+3', 'Europe/Minsk', 'Minsk'],
- ['Europe', '+3', 'Europe/Moscow', 'Moscow'],
- ['Europe', '+3', 'Europe/Simferopol', 'Simferopol'],
- ['Europe', '+4', 'Europe/Samara', 'Samara'],
- ['Europe', '+4', 'Europe/Volgograd', 'Volgograd'],
+ ['Europe', 'Europe/Dublin', 'Dublin'],
+ ['Europe', 'Europe/Guernsey', 'Guernsey'],
+ ['Europe', 'Europe/Isle_of_Man', 'Isle of Man'],
+ ['Europe', 'Europe/Jersey', 'Jersey'],
+ ['Europe', 'Europe/Lisbon', 'Lisbon'],
+ ['Europe', 'Europe/London', 'London'],
+ ['Europe', 'Europe/Amsterdam', 'Amsterdam'],
+ ['Europe', 'Europe/Andorra', 'Andorra'],
+ ['Europe', 'Europe/Belgrade', 'Belgrade'],
+ ['Europe', 'Europe/Berlin', 'Berlin'],
+ ['Europe', 'Europe/Bratislava', 'Bratislava'],
+ ['Europe', 'Europe/Brussels', 'Brussels'],
+ ['Europe', 'Europe/Budapest', 'Budapest'],
+ ['Europe', 'Europe/Busingen', 'Busingen'],
+ ['Europe', 'Europe/Copenhagen', 'Copenhagen'],
+ ['Europe', 'Europe/Gibraltar', 'Gibraltar'],
+ ['Europe', 'Europe/Ljubljana', 'Ljubljana'],
+ ['Europe', 'Europe/Luxembourg', 'Luxembourg'],
+ ['Europe', 'Europe/Madrid', 'Madrid'],
+ ['Europe', 'Europe/Malta', 'Malta'],
+ ['Europe', 'Europe/Monaco', 'Monaco'],
+ ['Europe', 'Europe/Oslo', 'Oslo'],
+ ['Europe', 'Europe/Paris', 'Paris'],
+ ['Europe', 'Europe/Podgorica', 'Podgorica'],
+ ['Europe', 'Europe/Prague', 'Prague'],
+ ['Europe', 'Europe/Rome', 'Rome'],
+ ['Europe', 'Europe/San_Marino', 'San Marino'],
+ ['Europe', 'Europe/Sarajevo', 'Sarajevo'],
+ ['Europe', 'Europe/Skopje', 'Skopje'],
+ ['Europe', 'Europe/Stockholm', 'Stockholm'],
+ ['Europe', 'Europe/Tirane', 'Tirane'],
+ ['Europe', 'Europe/Vaduz', 'Vaduz'],
+ ['Europe', 'Europe/Vatican', 'Vatican'],
+ ['Europe', 'Europe/Vienna', 'Vienna'],
+ ['Europe', 'Europe/Warsaw', 'Warsaw'],
+ ['Europe', 'Europe/Zagreb', 'Zagreb'],
+ ['Europe', 'Europe/Zurich', 'Zurich'],
+ ['Europe', 'Europe/Athens', 'Athens'],
+ ['Europe', 'Europe/Bucharest', 'Bucharest'],
+ ['Europe', 'Europe/Chisinau', 'Chisinau'],
+ ['Europe', 'Europe/Helsinki', 'Helsinki'],
+ ['Europe', 'Europe/Kaliningrad', 'Kaliningrad'],
+ ['Europe', 'Europe/Mariehamn', 'Mariehamn'],
+ ['Europe', 'Europe/Riga', 'Riga'],
+ ['Europe', 'Europe/Sofia', 'Sofia'],
+ ['Europe', 'Europe/Tallinn', 'Tallinn'],
+ ['Europe', 'Europe/Uzhgorod', 'Uzhgorod'],
+ ['Europe', 'Europe/Vilnius', 'Vilnius'],
+ ['Europe', 'Europe/Zaporozhye', 'Zaporozhye'],
+ ['Europe', 'Europe/Istanbul', 'Istanbul'],
+ ['Europe', 'Europe/Kiev', 'Kiev'],
+ ['Europe', 'Europe/Minsk', 'Minsk'],
+ ['Europe', 'Europe/Moscow', 'Moscow'],
+ ['Europe', 'Europe/Simferopol', 'Simferopol'],
+ ['Europe', 'Europe/Samara', 'Samara'],
+ ['Europe', 'Europe/Volgograd', 'Volgograd'],
- ['Asia', '+2', 'Asia/Amman', 'Amman'],
- ['Asia', '+2', 'Asia/Beirut', 'Beirut'],
- ['Asia', '+2', 'Asia/Damascus', 'Damascus'],
- ['Asia', '+2', 'Asia/Gaza', 'Gaza'],
- ['Asia', '+2', 'Asia/Hebron', 'Hebron'],
- ['Asia', '+2', 'Asia/Jerusalem', 'Jerusalem'],
- ['Asia', '+2', 'Asia/Nicosia', 'Nicosia'],
- ['Asia', '+3', 'Asia/Aden', 'Aden'],
- ['Asia', '+3', 'Asia/Baghdad', 'Baghdad'],
- ['Asia', '+3', 'Asia/Bahrain', 'Bahrain'],
- ['Asia', '+3', 'Asia/Kuwait', 'Kuwait'],
- ['Asia', '+3', 'Asia/Qatar', 'Qatar'],
- ['Asia', '+3', 'Asia/Riyadh', 'Riyadh'],
- ['Asia', '+3:30', 'Asia/Tehran', 'Tehran'],
- ['Asia', '+4', 'Asia/Baku', 'Baku'],
- ['Asia', '+4', 'Asia/Dubai', 'Dubai'],
- ['Asia', '+4', 'Asia/Muscat', 'Muscat'],
- ['Asia', '+4', 'Asia/Tbilisi', 'Tbilisi'],
- ['Asia', '+4', 'Asia/Yerevan', 'Yerevan'],
- ['Asia', '+4:30', 'Asia/Kabul', 'Kabul'],
- ['Asia', '+5', 'Asia/Aqtau', 'Aqtau'],
- ['Asia', '+5', 'Asia/Aqtobe', 'Aqtobe'],
- ['Asia', '+5', 'Asia/Ashgabat', 'Ashgabat'],
- ['Asia', '+5', 'Asia/Dushanbe', 'Dushanbe'],
- ['Asia', '+5', 'Asia/Karachi', 'Karachi'],
- ['Asia', '+5', 'Asia/Oral', 'Oral'],
- ['Asia', '+5', 'Asia/Samarkand', 'Samarkand'],
- ['Asia', '+5', 'Asia/Tashkent', 'Tashkent'],
- ['Asia', '+5', 'Asia/Yekaterinburg', 'Yekaterinburg'],
- ['Asia', '+5:30', 'Asia/Colombo', 'Colombo'],
- ['Asia', '+5:30', 'Asia/Kolkata', 'Kolkata'],
- ['Asia', '+5:45', 'Asia/Kathmandu', 'Kathmandu'],
- ['Asia', '+6', 'Asia/Almaty', 'Almaty'],
- ['Asia', '+6', 'Asia/Bishkek', 'Bishkek'],
- ['Asia', '+6', 'Asia/Dhaka', 'Dhaka'],
- ['Asia', '+6', 'Asia/Novosibirsk', 'Novosibirsk'],
- ['Asia', '+6', 'Asia/Omsk', 'Omsk'],
- ['Asia', '+6', 'Asia/Qyzylorda', 'Qyzylorda'],
- ['Asia', '+6', 'Asia/Thimphu', 'Thimphu'],
- ['Asia', '+6', 'Asia/Urumqi', 'Urumqi'],
- ['Asia', '+6:30', 'Asia/Rangoon', 'Rangoon'],
- ['Asia', '+7', 'Asia/Bangkok', 'Bangkok'],
- ['Asia', '+7', 'Asia/Ho_Chi_Minh', 'Ho Chi Minh'],
- ['Asia', '+7', 'Asia/Hovd', 'Hovd'],
- ['Asia', '+7', 'Asia/Jakarta', 'Jakarta'],
- ['Asia', '+7', 'Asia/Krasnoyarsk', 'Krasnoyarsk'],
- ['Asia', '+7', 'Asia/Novokuznetsk', 'Novokuznetsk'],
- ['Asia', '+7', 'Asia/Phnom_Penh', 'Phnom Penh'],
- ['Asia', '+7', 'Asia/Pontianak', 'Pontianak'],
- ['Asia', '+7', 'Asia/Vientiane', 'Vientiane'],
- ['Asia', '+8', 'Asia/Brunei', 'Brunei'],
- ['Asia', '+8', 'Asia/Choibalsan', 'Choibalsan'],
- ['Asia', '+8', 'Asia/Hong_Kong', 'Hong Kong'],
- ['Asia', '+8', 'Asia/Irkutsk', 'Irkutsk'],
- ['Asia', '+8', 'Asia/Kuala_Lumpur', 'Kuala Lumpur'],
- ['Asia', '+8', 'Asia/Kuching', 'Kuching'],
- ['Asia', '+8', 'Asia/Macau', 'Macau'],
- ['Asia', '+8', 'Asia/Makassar', 'Makassar'],
- ['Asia', '+8', 'Asia/Manila', 'Manila'],
- ['Asia', '+8', 'Asia/Shanghai', 'Shanghai'],
- ['Asia', '+8', 'Asia/Singapore', 'Singapore'],
- ['Asia', '+8', 'Asia/Taipei', 'Taipei'],
- ['Asia', '+8', 'Asia/Ulaanbaatar', 'Ulaanbaatar'],
- ['Asia', '+9', 'Asia/Chita', 'Chita'],
- ['Asia', '+9', 'Asia/Dili', 'Dili'],
- ['Asia', '+9', 'Asia/Jayapura', 'Jayapura'],
- ['Asia', '+9', 'Asia/Khandyga', 'Khandyga'],
- ['Asia', '+9', 'Asia/Pyongyang', 'Pyongyang'],
- ['Asia', '+9', 'Asia/Seoul', 'Seoul'],
- ['Asia', '+9', 'Asia/Tokyo', 'Tokyo'],
- ['Asia', '+9', 'Asia/Yakutsk', 'Yakutsk'],
- ['Asia', '+10', 'Asia/Magadan', 'Magadan'],
- ['Asia', '+10', 'Asia/Sakhalin', 'Sakhalin'],
- ['Asia', '+10', 'Asia/Ust-Nera', 'Ust-Nera'],
- ['Asia', '+10', 'Asia/Vladivostok', 'Vladivostok'],
- ['Asia', '+11', 'Asia/Srednekolymsk', 'Srednekolymsk'],
- ['Asia', '+12', 'Asia/Anadyr', 'Anadyr'],
- ['Asia', '+12', 'Asia/Kamchatka', 'Kamchatka'],
+ ['Asia', 'Asia/Amman', 'Amman'],
+ ['Asia', 'Asia/Beirut', 'Beirut'],
+ ['Asia', 'Asia/Damascus', 'Damascus'],
+ ['Asia', 'Asia/Gaza', 'Gaza'],
+ ['Asia', 'Asia/Hebron', 'Hebron'],
+ ['Asia', 'Asia/Jerusalem', 'Jerusalem'],
+ ['Asia', 'Asia/Nicosia', 'Nicosia'],
+ ['Asia', 'Asia/Aden', 'Aden'],
+ ['Asia', 'Asia/Baghdad', 'Baghdad'],
+ ['Asia', 'Asia/Bahrain', 'Bahrain'],
+ ['Asia', 'Asia/Kuwait', 'Kuwait'],
+ ['Asia', 'Asia/Qatar', 'Qatar'],
+ ['Asia', 'Asia/Riyadh', 'Riyadh'],
+ ['Asia', 'Asia/Tehran', 'Tehran'],
+ ['Asia', 'Asia/Baku', 'Baku'],
+ ['Asia', 'Asia/Dubai', 'Dubai'],
+ ['Asia', 'Asia/Muscat', 'Muscat'],
+ ['Asia', 'Asia/Tbilisi', 'Tbilisi'],
+ ['Asia', 'Asia/Yerevan', 'Yerevan'],
+ ['Asia', 'Asia/Kabul', 'Kabul'],
+ ['Asia', 'Asia/Aqtau', 'Aqtau'],
+ ['Asia', 'Asia/Aqtobe', 'Aqtobe'],
+ ['Asia', 'Asia/Ashgabat', 'Ashgabat'],
+ ['Asia', 'Asia/Dushanbe', 'Dushanbe'],
+ ['Asia', 'Asia/Karachi', 'Karachi'],
+ ['Asia', 'Asia/Oral', 'Oral'],
+ ['Asia', 'Asia/Samarkand', 'Samarkand'],
+ ['Asia', 'Asia/Tashkent', 'Tashkent'],
+ ['Asia', 'Asia/Yekaterinburg', 'Yekaterinburg'],
+ ['Asia', 'Asia/Colombo', 'Colombo'],
+ ['Asia', 'Asia/Kolkata', 'Kolkata'],
+ ['Asia', 'Asia/Kathmandu', 'Kathmandu'],
+ ['Asia', 'Asia/Almaty', 'Almaty'],
+ ['Asia', 'Asia/Bishkek', 'Bishkek'],
+ ['Asia', 'Asia/Dhaka', 'Dhaka'],
+ ['Asia', 'Asia/Novosibirsk', 'Novosibirsk'],
+ ['Asia', 'Asia/Omsk', 'Omsk'],
+ ['Asia', 'Asia/Qyzylorda', 'Qyzylorda'],
+ ['Asia', 'Asia/Thimphu', 'Thimphu'],
+ ['Asia', 'Asia/Urumqi', 'Urumqi'],
+ ['Asia', 'Asia/Rangoon', 'Rangoon'],
+ ['Asia', 'Asia/Bangkok', 'Bangkok'],
+ ['Asia', 'Asia/Ho_Chi_Minh', 'Ho Chi Minh'],
+ ['Asia', 'Asia/Hovd', 'Hovd'],
+ ['Asia', 'Asia/Jakarta', 'Jakarta'],
+ ['Asia', 'Asia/Krasnoyarsk', 'Krasnoyarsk'],
+ ['Asia', 'Asia/Novokuznetsk', 'Novokuznetsk'],
+ ['Asia', 'Asia/Phnom_Penh', 'Phnom Penh'],
+ ['Asia', 'Asia/Pontianak', 'Pontianak'],
+ ['Asia', 'Asia/Vientiane', 'Vientiane'],
+ ['Asia', 'Asia/Brunei', 'Brunei'],
+ ['Asia', 'Asia/Choibalsan', 'Choibalsan'],
+ ['Asia', 'Asia/Hong_Kong', 'Hong Kong'],
+ ['Asia', 'Asia/Irkutsk', 'Irkutsk'],
+ ['Asia', 'Asia/Kuala_Lumpur', 'Kuala Lumpur'],
+ ['Asia', 'Asia/Kuching', 'Kuching'],
+ ['Asia', 'Asia/Macau', 'Macau'],
+ ['Asia', 'Asia/Makassar', 'Makassar'],
+ ['Asia', 'Asia/Manila', 'Manila'],
+ ['Asia', 'Asia/Shanghai', 'Shanghai'],
+ ['Asia', 'Asia/Singapore', 'Singapore'],
+ ['Asia', 'Asia/Taipei', 'Taipei'],
+ ['Asia', 'Asia/Ulaanbaatar', 'Ulaanbaatar'],
+ ['Asia', 'Asia/Chita', 'Chita'],
+ ['Asia', 'Asia/Dili', 'Dili'],
+ ['Asia', 'Asia/Jayapura', 'Jayapura'],
+ ['Asia', 'Asia/Khandyga', 'Khandyga'],
+ ['Asia', 'Asia/Pyongyang', 'Pyongyang'],
+ ['Asia', 'Asia/Seoul', 'Seoul'],
+ ['Asia', 'Asia/Tokyo', 'Tokyo'],
+ ['Asia', 'Asia/Yakutsk', 'Yakutsk'],
+ ['Asia', 'Asia/Magadan', 'Magadan'],
+ ['Asia', 'Asia/Sakhalin', 'Sakhalin'],
+ ['Asia', 'Asia/Ust-Nera', 'Ust-Nera'],
+ ['Asia', 'Asia/Vladivostok', 'Vladivostok'],
+ ['Asia', 'Asia/Srednekolymsk', 'Srednekolymsk'],
+ ['Asia', 'Asia/Anadyr', 'Anadyr'],
+ ['Asia', 'Asia/Kamchatka', 'Kamchatka'],
- ['Australia', '+8', 'Australia/Perth', 'Perth'],
- ['Australia', '+8:45', 'Australia/Eucla', 'Eucla'],
- ['Australia', '+9:30', 'Australia/Darwin', 'Darwin'],
- ['Australia', '+10', 'Australia/Brisbane', 'Brisbane'],
- ['Australia', '+10', 'Australia/Lindeman', 'Lindeman'],
- ['Australia', '+10:30', 'Australia/Adelaide', 'Adelaide'],
- ['Australia', '+10', 'Australia/Broken_Hill', 'Broken Hill'],
- ['Australia', '+11', 'Australia/Currie', 'Currie'],
- ['Australia', '+11', 'Australia/Hobart', 'Hobart'],
- ['Australia', '+11', 'Australia/Lord_Howe', 'Lord_Howe'],
- ['Australia', '+11', 'Australia/Melbourne', 'Melbourne'],
- ['Australia', '+11', 'Australia/Sydney', 'Sydney'],
+ ['Australia', 'Australia/Perth', 'Perth'],
+ ['Australia', 'Australia/Eucla', 'Eucla'],
+ ['Australia', 'Australia/Darwin', 'Darwin'],
+ ['Australia', 'Australia/Brisbane', 'Brisbane'],
+ ['Australia', 'Australia/Lindeman', 'Lindeman'],
+ ['Australia', 'Australia/Adelaide', 'Adelaide'],
+ ['Australia', 'Australia/Broken_Hill', 'Broken Hill'],
+ ['Australia', 'Australia/Currie', 'Currie'],
+ ['Australia', 'Australia/Hobart', 'Hobart'],
+ ['Australia', 'Australia/Lord_Howe', 'Lord_Howe'],
+ ['Australia', 'Australia/Melbourne', 'Melbourne'],
+ ['Australia', 'Australia/Sydney', 'Sydney'],
- ['Indian', '+3', 'Indian/Antananarivo', 'Antananarivo'],
- ['Indian', '+3', 'Indian/Comoro', 'Comoro'],
- ['Indian', '+3', 'Indian/Mayotte', 'Mayotte'],
- ['Indian', '+4', 'Indian/Mahe', 'Mahe'],
- ['Indian', '+4', 'Indian/Mauritius', 'Mauritius'],
- ['Indian', '+4', 'Indian/Reunion', 'Reunion'],
- ['Indian', '+5', 'Indian/Kerguelen', 'Kerguelen'],
- ['Indian', '+5', 'Indian/Maldives', 'Maldives'],
- ['Indian', '+6', 'Indian/Chagos', 'Chagos'],
- ['Indian', '+6:30', 'Indian/Cocos', 'Cocos'],
- ['Indian', '+7', 'Indian/Christmas', 'Christmas'],
+ ['Indian', 'Indian/Antananarivo', 'Antananarivo'],
+ ['Indian', 'Indian/Comoro', 'Comoro'],
+ ['Indian', 'Indian/Mayotte', 'Mayotte'],
+ ['Indian', 'Indian/Mahe', 'Mahe'],
+ ['Indian', 'Indian/Mauritius', 'Mauritius'],
+ ['Indian', 'Indian/Reunion', 'Reunion'],
+ ['Indian', 'Indian/Kerguelen', 'Kerguelen'],
+ ['Indian', 'Indian/Maldives', 'Maldives'],
+ ['Indian', 'Indian/Chagos', 'Chagos'],
+ ['Indian', 'Indian/Cocos', 'Cocos'],
+ ['Indian', 'Indian/Christmas', 'Christmas'],
- ['Africa', '+0', 'Africa/Abidjan', 'Abidjan'],
- ['Africa', '+0', 'Africa/Accra', 'Accra'],
- ['Africa', '+0', 'Africa/Bamako', 'Bamako'],
- ['Africa', '+0', 'Africa/Banjul', 'Banjul'],
- ['Africa', '+0', 'Africa/Bissau', 'Bissau'],
- ['Africa', '+0', 'Africa/Casablanca', 'Casablanca'],
- ['Africa', '+0', 'Africa/Conakry', 'Conakry'],
- ['Africa', '+0', 'Africa/Dakar', 'Dakar'],
- ['Africa', '+0', 'Africa/El_Aaiun', 'El Aaiun'],
- ['Africa', '+0', 'Africa/Freetown', 'Freetown'],
- ['Africa', '+0', 'Africa/Lome', 'Lome'],
- ['Africa', '+0', 'Africa/Monrovia', 'Monrovia'],
- ['Africa', '+0', 'Africa/Nouakchott', 'Nouakchott'],
- ['Africa', '+0', 'Africa/Ouagadougou', 'Ouagadougou'],
- ['Africa', '+0', 'Africa/Sao_Tome', 'Sao Tome'],
- ['Africa', '+1', 'Africa/Algiers', 'Algiers'],
- ['Africa', '+1', 'Africa/Bangui', 'Bangui'],
- ['Africa', '+1', 'Africa/Brazzaville', 'Brazzaville'],
- ['Africa', '+1', 'Africa/Ceuta', 'Ceuta'],
- ['Africa', '+1', 'Africa/Douala', 'Douala'],
- ['Africa', '+1', 'Africa/Kinshasa', 'Kinshasa'],
- ['Africa', '+1', 'Africa/Lagos', 'Lagos'],
- ['Africa', '+1', 'Africa/Libreville', 'Libreville'],
- ['Africa', '+1', 'Africa/Luanda', 'Luanda'],
- ['Africa', '+1', 'Africa/Malabo', 'Malabo'],
- ['Africa', '+1', 'Africa/Ndjamena', 'Ndjamena'],
- ['Africa', '+1', 'Africa/Niamey', 'Niamey'],
- ['Africa', '+1', 'Africa/Porto-Novo', 'Porto-Novo'],
- ['Africa', '+1', 'Africa/Tunis', 'Tunis'],
- ['Africa', '+2', 'Africa/Blantyre', 'Blantyre'],
- ['Africa', '+2', 'Africa/Bujumbura', 'Bujumbura'],
- ['Africa', '+2', 'Africa/Cairo', 'Cairo'],
- ['Africa', '+2', 'Africa/Gaborone', 'Gaborone'],
- ['Africa', '+2', 'Africa/Harare', 'Harare'],
- ['Africa', '+2', 'Africa/Johannesburg', 'Johannesburg'],
- ['Africa', '+2', 'Africa/Juba', 'Juba'],
- ['Africa', '+2', 'Africa/Khartoum', 'Khartoum'],
- ['Africa', '+2', 'Africa/Kigali', 'Kigali'],
- ['Africa', '+2', 'Africa/Lubumbashi', 'Lubumbashi'],
- ['Africa', '+2', 'Africa/Lusaka', 'Lusaka'],
- ['Africa', '+2', 'Africa/Maputo', 'Maputo'],
- ['Africa', '+2', 'Africa/Maseru', 'Maseru'],
- ['Africa', '+2', 'Africa/Mbabane', 'Mbabane'],
- ['Africa', '+2', 'Africa/Tripoli', 'Tripoli'],
- ['Africa', '+2', 'Africa/Windhoek', 'Windhoek'],
- ['Africa', '+3', 'Africa/Addis_Ababa', 'Addis Ababa'],
- ['Africa', '+3', 'Africa/Asmara', 'Asmara'],
- ['Africa', '+3', 'Africa/Dar_es_Salaam', 'Dar es Salaam'],
- ['Africa', '+3', 'Africa/Djibouti', 'Djibouti'],
- ['Africa', '+3', 'Africa/Kampala', 'Kampala'],
- ['Africa', '+3', 'Africa/Mogadishu', 'Mogadishu'],
- ['Africa', '+3', 'Africa/Nairobi', 'Nairobi'],
+ ['Africa', 'Africa/Abidjan', 'Abidjan'],
+ ['Africa', 'Africa/Accra', 'Accra'],
+ ['Africa', 'Africa/Bamako', 'Bamako'],
+ ['Africa', 'Africa/Banjul', 'Banjul'],
+ ['Africa', 'Africa/Bissau', 'Bissau'],
+ ['Africa', 'Africa/Casablanca', 'Casablanca'],
+ ['Africa', 'Africa/Conakry', 'Conakry'],
+ ['Africa', 'Africa/Dakar', 'Dakar'],
+ ['Africa', 'Africa/El_Aaiun', 'El Aaiun'],
+ ['Africa', 'Africa/Freetown', 'Freetown'],
+ ['Africa', 'Africa/Lome', 'Lome'],
+ ['Africa', 'Africa/Monrovia', 'Monrovia'],
+ ['Africa', 'Africa/Nouakchott', 'Nouakchott'],
+ ['Africa', 'Africa/Ouagadougou', 'Ouagadougou'],
+ ['Africa', 'Africa/Sao_Tome', 'Sao Tome'],
+ ['Africa', 'Africa/Algiers', 'Algiers'],
+ ['Africa', 'Africa/Bangui', 'Bangui'],
+ ['Africa', 'Africa/Brazzaville', 'Brazzaville'],
+ ['Africa', 'Africa/Ceuta', 'Ceuta'],
+ ['Africa', 'Africa/Douala', 'Douala'],
+ ['Africa', 'Africa/Kinshasa', 'Kinshasa'],
+ ['Africa', 'Africa/Lagos', 'Lagos'],
+ ['Africa', 'Africa/Libreville', 'Libreville'],
+ ['Africa', 'Africa/Luanda', 'Luanda'],
+ ['Africa', 'Africa/Malabo', 'Malabo'],
+ ['Africa', 'Africa/Ndjamena', 'Ndjamena'],
+ ['Africa', 'Africa/Niamey', 'Niamey'],
+ ['Africa', 'Africa/Porto-Novo', 'Porto-Novo'],
+ ['Africa', 'Africa/Tunis', 'Tunis'],
+ ['Africa', 'Africa/Blantyre', 'Blantyre'],
+ ['Africa', 'Africa/Bujumbura', 'Bujumbura'],
+ ['Africa', 'Africa/Cairo', 'Cairo'],
+ ['Africa', 'Africa/Gaborone', 'Gaborone'],
+ ['Africa', 'Africa/Harare', 'Harare'],
+ ['Africa', 'Africa/Johannesburg', 'Johannesburg'],
+ ['Africa', 'Africa/Juba', 'Juba'],
+ ['Africa', 'Africa/Khartoum', 'Khartoum'],
+ ['Africa', 'Africa/Kigali', 'Kigali'],
+ ['Africa', 'Africa/Lubumbashi', 'Lubumbashi'],
+ ['Africa', 'Africa/Lusaka', 'Lusaka'],
+ ['Africa', 'Africa/Maputo', 'Maputo'],
+ ['Africa', 'Africa/Maseru', 'Maseru'],
+ ['Africa', 'Africa/Mbabane', 'Mbabane'],
+ ['Africa', 'Africa/Tripoli', 'Tripoli'],
+ ['Africa', 'Africa/Windhoek', 'Windhoek'],
+ ['Africa', 'Africa/Addis_Ababa', 'Addis Ababa'],
+ ['Africa', 'Africa/Asmara', 'Asmara'],
+ ['Africa', 'Africa/Dar_es_Salaam', 'Dar es Salaam'],
+ ['Africa', 'Africa/Djibouti', 'Djibouti'],
+ ['Africa', 'Africa/Kampala', 'Kampala'],
+ ['Africa', 'Africa/Mogadishu', 'Mogadishu'],
+ ['Africa', 'Africa/Nairobi', 'Nairobi'],
- ['Pacific', '+9', 'Pacific/Palau', 'Palau'],
- ['Pacific', '+10', 'Pacific/Chuuk', 'Chuuk'],
- ['Pacific', '+10', 'Pacific/Guam', 'Guam'],
- ['Pacific', '+10', 'Pacific/Port_Moresby', 'Port Moresby'],
- ['Pacific', '+10', 'Pacific/Saipan', 'Saipan'],
- ['Pacific', '+11', 'Pacific/Bougainville', 'Bougainville'],
- ['Pacific', '+11', 'Pacific/Efate', 'Efate'],
- ['Pacific', '+11', 'Pacific/Guadalcanal', 'Guadalcanal'],
- ['Pacific', '+11', 'Pacific/Kosrae', 'Kosrae'],
- ['Pacific', '+11', 'Pacific/Norfolk', 'Norfolk'],
- ['Pacific', '+11', 'Pacific/Noumea', 'Noumea'],
- ['Pacific', '+11', 'Pacific/Pohnpei', 'Pohnpei'],
- ['Pacific', '+12', 'Pacific/Funafuti', 'Funafuti'],
- ['Pacific', '+12', 'Pacific/Kwajalein', 'Kwajalein'],
- ['Pacific', '+12', 'Pacific/Majuro', 'Majuro'],
- ['Pacific', '+12', 'Pacific/Nauru', 'Nauru'],
- ['Pacific', '+12', 'Pacific/Tarawa', 'Tarawa'],
- ['Pacific', '+12', 'Pacific/Wake', 'Wake'],
- ['Pacific', '+12', 'Pacific/Wallis', 'Wallis'],
- ['Pacific', '+13', 'Pacific/Auckland', 'Auckland'],
- ['Pacific', '+13', 'Pacific/Enderbury', 'Enderbury'],
- ['Pacific', '+13', 'Pacific/Fakaofo', 'Fakaofo'],
- ['Pacific', '+13', 'Pacific/Fiji', 'Fiji'],
- ['Pacific', '+13', 'Pacific/Tongatapu', 'Tongatapu'],
- ['Pacific', '+13:45', 'Pacific/Chatham', 'Chatham'],
- ['Pacific', '+14', 'Pacific/Apia', 'Apia'],
- ['Pacific', '+14', 'Pacific/Kiritimati', 'Kiritimati'],
- ['Pacific', '-5', 'Pacific/Easter', 'Easter'],
- ['Pacific', '-6', 'Pacific/Galapagos', 'Galapagos'],
- ['Pacific', '-8', 'Pacific/Pitcairn', 'Pitcairn'],
- ['Pacific', '-9', 'Pacific/Gambier', 'Gambier'],
- ['Pacific', '-9:30', 'Pacific/Marquesas', 'Marquesas'],
- ['Pacific', '-10', 'Pacific/Honolulu', 'Honolulu'],
- ['Pacific', '-10', 'Pacific/Johnston', 'Johnston'],
- ['Pacific', '-10', 'Pacific/Rarotonga', 'Rarotonga'],
- ['Pacific', '-10', 'Pacific/Tahiti', 'Tahiti'],
- ['Pacific', '-11', 'Pacific/Midway', 'Midway'],
- ['Pacific', '-11', 'Pacific/Niue', 'Niue'],
- ['Pacific', '-11', 'Pacific/Pago_Pago', 'Pago Pago'],
+ ['Pacific', 'Pacific/Palau', 'Palau'],
+ ['Pacific', 'Pacific/Chuuk', 'Chuuk'],
+ ['Pacific', 'Pacific/Guam', 'Guam'],
+ ['Pacific', 'Pacific/Port_Moresby', 'Port Moresby'],
+ ['Pacific', 'Pacific/Saipan', 'Saipan'],
+ ['Pacific', 'Pacific/Bougainville', 'Bougainville'],
+ ['Pacific', 'Pacific/Efate', 'Efate'],
+ ['Pacific', 'Pacific/Guadalcanal', 'Guadalcanal'],
+ ['Pacific', 'Pacific/Kosrae', 'Kosrae'],
+ ['Pacific', 'Pacific/Norfolk', 'Norfolk'],
+ ['Pacific', 'Pacific/Noumea', 'Noumea'],
+ ['Pacific', 'Pacific/Pohnpei', 'Pohnpei'],
+ ['Pacific', 'Pacific/Funafuti', 'Funafuti'],
+ ['Pacific', 'Pacific/Kwajalein', 'Kwajalein'],
+ ['Pacific', 'Pacific/Majuro', 'Majuro'],
+ ['Pacific', 'Pacific/Nauru', 'Nauru'],
+ ['Pacific', 'Pacific/Tarawa', 'Tarawa'],
+ ['Pacific', 'Pacific/Wake', 'Wake'],
+ ['Pacific', 'Pacific/Wallis', 'Wallis'],
+ ['Pacific', 'Pacific/Auckland', 'Auckland'],
+ ['Pacific', 'Pacific/Enderbury', 'Enderbury'],
+ ['Pacific', 'Pacific/Fakaofo', 'Fakaofo'],
+ ['Pacific', 'Pacific/Fiji', 'Fiji'],
+ ['Pacific', 'Pacific/Tongatapu', 'Tongatapu'],
+ ['Pacific', 'Pacific/Chatham', 'Chatham'],
+ ['Pacific', 'Pacific/Apia', 'Apia'],
+ ['Pacific', 'Pacific/Kiritimati', 'Kiritimati'],
+ ['Pacific', 'Pacific/Easter', 'Easter'],
+ ['Pacific', 'Pacific/Galapagos', 'Galapagos'],
+ ['Pacific', 'Pacific/Pitcairn', 'Pitcairn'],
+ ['Pacific', 'Pacific/Gambier', 'Gambier'],
+ ['Pacific', 'Pacific/Marquesas', 'Marquesas'],
+ ['Pacific', 'Pacific/Honolulu', 'Honolulu'],
+ ['Pacific', 'Pacific/Johnston', 'Johnston'],
+ ['Pacific', 'Pacific/Rarotonga', 'Rarotonga'],
+ ['Pacific', 'Pacific/Tahiti', 'Tahiti'],
+ ['Pacific', 'Pacific/Midway', 'Midway'],
+ ['Pacific', 'Pacific/Niue', 'Niue'],
+ ['Pacific', 'Pacific/Pago_Pago', 'Pago Pago'],
- ['Atlantic', '+0', 'Atlantic/Canary', 'Canary'],
- ['Atlantic', '+0', 'Atlantic/Faroe', 'Faroe'],
- ['Atlantic', '+0', 'Atlantic/Madeira', 'Madeira'],
- ['Atlantic', '+0', 'Atlantic/Reykjavik', 'Reykjavik'],
- ['Atlantic', '+0', 'Atlantic/St_Helena', 'St Helena'],
- ['Atlantic', '-1', 'Atlantic/Azores', 'Azores'],
- ['Atlantic', '-1', 'Atlantic/Cape_Verde', 'Cape Verde'],
- ['Atlantic', '-2', 'Atlantic/South_Georgia', 'South Georgia'],
- ['Atlantic', '-3', 'Atlantic/Stanley', 'Stanley'],
- ['Atlantic', '-4', 'Atlantic/Bermuda', 'Bermuda'],
+ ['Atlantic', 'Atlantic/Canary', 'Canary'],
+ ['Atlantic', 'Atlantic/Faroe', 'Faroe'],
+ ['Atlantic', 'Atlantic/Madeira', 'Madeira'],
+ ['Atlantic', 'Atlantic/Reykjavik', 'Reykjavik'],
+ ['Atlantic', 'Atlantic/St_Helena', 'St Helena'],
+ ['Atlantic', 'Atlantic/Azores', 'Azores'],
+ ['Atlantic', 'Atlantic/Cape_Verde', 'Cape Verde'],
+ ['Atlantic', 'Atlantic/South_Georgia', 'South Georgia'],
+ ['Atlantic', 'Atlantic/Stanley', 'Stanley'],
+ ['Atlantic', 'Atlantic/Bermuda', 'Bermuda'],
- ['Antarctica', '+0', 'Antarctica/Troll', 'Troll'],
- ['Antarctica', '+3', 'Antarctica/Syowa', 'Syowa'],
- ['Antarctica', '+5', 'Antarctica/Mawson', 'Mawson'],
- ['Antarctica', '+6', 'Antarctica/Vostok', 'Vostok'],
- ['Antarctica', '+7', 'Antarctica/Davis', 'Davis'],
- ['Antarctica', '+8', 'Antarctica/Casey', 'Casey'],
- ['Antarctica', '+10', 'Antarctica/DumontDUrville', 'DumontDUrville'],
- ['Antarctica', '+11', 'Antarctica/Macquarie', 'Macquarie'],
- ['Antarctica', '+13', 'Antarctica/McMurdo', 'McMurdo'],
- ['Antarctica', '-3', 'Antarctica/Palmer', 'Palmer'],
- ['Antarctica', '-3', 'Antarctica/Rothera', 'Rothera'],
- ['Arctic', '+1', 'Arctic/Longyearbyen', 'Longyearbyen'],
+ ['Antarctica', 'Antarctica/Troll', 'Troll'],
+ ['Antarctica', 'Antarctica/Syowa', 'Syowa'],
+ ['Antarctica', 'Antarctica/Mawson', 'Mawson'],
+ ['Antarctica', 'Antarctica/Vostok', 'Vostok'],
+ ['Antarctica', 'Antarctica/Davis', 'Davis'],
+ ['Antarctica', 'Antarctica/Casey', 'Casey'],
+ ['Antarctica', 'Antarctica/DumontDUrville', 'DumontDUrville'],
+ ['Antarctica', 'Antarctica/Macquarie', 'Macquarie'],
+ ['Antarctica', 'Antarctica/McMurdo', 'McMurdo'],
+ ['Antarctica', 'Antarctica/Palmer', 'Palmer'],
+ ['Antarctica', 'Antarctica/Rothera', 'Rothera'],
+ ['Arctic', 'Arctic/Longyearbyen', 'Longyearbyen'],
];
const OffsetLabel = styled('div')`
@@ -482,12 +478,15 @@ const groupedTimezones = Object.entries(groupBy(timezones, ([group]) => group));
// @ts-expect-error Should be removed once these types improve for grouped options
const timezoneOptions: SelectValue<string>[] = groupedTimezones.map(([group, zones]) => ({
label: group,
- options: zones.map(([_, offsetLabel, value, label]) => ({
- value,
- trailingItems: <OffsetLabel>UTC {offsetLabel}</OffsetLabel>,
- label,
- textValue: `${group} ${label} ${offsetLabel}`,
- })),
+ options: zones.map(([_, value, label]) => {
+ const offsetLabel = moment.tz(value).format('Z');
+ return {
+ value,
+ trailingItems: <OffsetLabel>UTC {offsetLabel}</OffsetLabel>,
+ label,
+ textValue: `${group} ${label} ${offsetLabel}`,
+ };
+ }),
}));
export {timezones, timezoneOptions};
|
9a748f778f6c1ec8eeb08b6910a853820fc782ad
|
2017-09-26 03:51:44
|
Billy Vong
|
fix(ui): Fix rate limit css for firefox (#6188)
| false
|
Fix rate limit css for firefox (#6188)
|
fix
|
diff --git a/src/sentry/static/sentry/app/views/projectKeyDetails.jsx b/src/sentry/static/sentry/app/views/projectKeyDetails.jsx
index b653b456ac4d7f..fb395ed935588e 100644
--- a/src/sentry/static/sentry/app/views/projectKeyDetails.jsx
+++ b/src/sentry/static/sentry/app/views/projectKeyDetails.jsx
@@ -8,6 +8,7 @@ import idx from 'idx';
import ApiMixin from '../mixins/apiMixin';
import AutoSelectText from '../components/autoSelectText';
import DateTime from '../components/dateTime';
+import FlowLayout from '../components/flowLayout';
import HookStore from '../stores/hookStore';
import IndicatorStore from '../stores/indicatorStore';
import LoadingError from '../components/loadingError';
@@ -321,10 +322,10 @@ const KeySettings = React.createClass({
'Rate limits provide a flexible way to manage your event volume. If you have a noisy project or environment you can configure a rate limit for this key to reduce the number of events processed.'
}
</p>
- <div className="form-group">
+ <div className="form-group rate-limit-group">
<label>{t('Rate Limit')}</label>
- <div>
- <div style={{width: 80, display: 'inline-block'}}>
+ <FlowLayout>
+ <div style={{width: 80}}>
<NumberField
key="rateLimit.count"
name="rateLimit.count"
@@ -337,10 +338,10 @@ const KeySettings = React.createClass({
className=""
/>
</div>
- <div style={{display: 'inline-block', margin: '0 10px'}}>
+ <div style={{margin: '0 10px'}}>
<small>event(s) in</small>
</div>
- <div style={{width: 150, display: 'inline-block'}}>
+ <div style={{width: 150}}>
<Select2Field
width="100%"
key="rateLimit.window"
@@ -355,11 +356,12 @@ const KeySettings = React.createClass({
className=""
/>
</div>
- <div className="help-block">
- {t(
- 'Apply a rate limit to this credential to cap the amount of events accepted during a time window.'
- )}
- </div>
+ </FlowLayout>
+
+ <div className="help-block">
+ {t(
+ 'Apply a rate limit to this credential to cap the amount of events accepted during a time window.'
+ )}
</div>
</div>
<fieldset className="form-actions">
diff --git a/src/sentry/static/sentry/less/forms.less b/src/sentry/static/sentry/less/forms.less
index f6e9c7880f5f56..c30d4fd2c89a2e 100644
--- a/src/sentry/static/sentry/less/forms.less
+++ b/src/sentry/static/sentry/less/forms.less
@@ -54,6 +54,12 @@
margin-bottom: 15px;
}
+.rate-limit-group {
+ .control-group {
+ margin-bottom: 0;
+ }
+}
+
.form-actions {
border-top: 1px solid #E9EBEC;
background: none;
|
4c8da8997e37c2643a16aa0ed5a12f53fe8622ec
|
2021-06-14 22:56:16
|
Evan Purkhiser
|
ref(search): Avoid directly calling visitors (#26580)
| false
|
Avoid directly calling visitors (#26580)
|
ref
|
diff --git a/src/sentry/api/event_search.py b/src/sentry/api/event_search.py
index 7098acfe3169c9..7633685ce72029 100644
--- a/src/sentry/api/event_search.py
+++ b/src/sentry/api/event_search.py
@@ -436,7 +436,7 @@ def visit_paren_group(self, node, children):
if not self.allow_boolean:
# It's possible to have a valid search that includes parens, so we
# can't just error out when we find a paren expression.
- return self.visit_free_text(node, children)
+ return SearchFilter(SearchKey("message"), "=", SearchValue(node.text))
children = remove_space(remove_optional_nodes(flatten(children)))
children = flatten(children[1])
@@ -465,6 +465,23 @@ def _handle_basic_filter(self, search_key, operator, search_value):
return SearchFilter(search_key, operator, search_value)
+ def _handle_numeric_filter(self, search_key, operator, search_value):
+ if isinstance(operator, Node):
+ operator = "=" if isinstance(operator.expr, Optional) else operator.text
+ else:
+ operator = operator[0]
+
+ if self.is_numeric_key(search_key.name):
+ try:
+ search_value = SearchValue(parse_numeric_value(*search_value))
+ except InvalidQuery as exc:
+ raise InvalidSearchQuery(str(exc))
+ return SearchFilter(search_key, operator, search_value)
+
+ search_value = "".join(search_value)
+ search_value = SearchValue(operator + search_value if operator != "=" else search_value)
+ return self._handle_basic_filter(search_key, "=", search_value)
+
def visit_date_filter(self, node, children):
(search_key, _, operator, search_value) = children
@@ -534,8 +551,8 @@ def visit_duration_filter(self, node, children):
return SearchFilter(search_key, operator, SearchValue(search_value))
# Durations overlap with numeric `m` suffixes
- elif self.is_numeric_key(search_key.name):
- return self.visit_numeric_filter(node, (search_key, sep, operator, search_value))
+ if self.is_numeric_key(search_key.name):
+ return self._handle_numeric_filter(search_key, operator, search_value)
search_value = "".join(search_value)
search_value = operator + search_value if operator != "=" else search_value
@@ -547,15 +564,7 @@ def visit_boolean_filter(self, node, children):
# Numeric and boolean filters overlap on 1 and 0 values.
if self.is_numeric_key(search_key.name):
- return self.visit_numeric_filter(
- node,
- (
- search_key,
- sep,
- "=",
- [search_value.text, ""],
- ),
- )
+ return self._handle_numeric_filter(search_key, "=", [search_value.text, ""])
if search_key.name in self.boolean_keys:
if search_value.text.lower() in ("true", "1"):
@@ -585,21 +594,7 @@ def visit_numeric_in_filter(self, node, children):
def visit_numeric_filter(self, node, children):
(search_key, _, operator, search_value) = children
- if isinstance(operator, Node):
- operator = "=" if isinstance(operator.expr, Optional) else operator.text
- else:
- operator = operator[0]
-
- if self.is_numeric_key(search_key.name):
- try:
- search_value = SearchValue(parse_numeric_value(*search_value))
- except InvalidQuery as exc:
- raise InvalidSearchQuery(str(exc))
- return SearchFilter(search_key, operator, search_value)
-
- search_value = "".join(search_value)
- search_value = SearchValue(operator + search_value if operator != "=" else search_value)
- return self._handle_basic_filter(search_key, "=", search_value)
+ return self._handle_numeric_filter(search_key, operator, search_value)
def visit_aggregate_filter(self, node, children):
(negation, search_key, _, operator, search_value) = children
|
18884dbd4c42367749f4f16deb8a2825965b9a5f
|
2023-10-18 04:06:05
|
Katie Byers
|
feat(severity): Add support for backlog testing (#58297)
| false
|
Add support for backlog testing (#58297)
|
feat
|
diff --git a/src/sentry/event_manager.py b/src/sentry/event_manager.py
index 4eb8b2c7fc71a1..4816eb280a9f13 100644
--- a/src/sentry/event_manager.py
+++ b/src/sentry/event_manager.py
@@ -2101,6 +2101,12 @@ def _get_severity_score(event: Event) -> float | None:
# we should update the model to account for three values: True, False, and None
"handled": 0 if is_handled(event.data) is False else 1,
}
+
+ if options.get("processing.severity-backlog-test.timeout"):
+ payload["trigger_timeout"] = True
+ if options.get("processing.severity-backlog-test.error"):
+ payload["trigger_error"] = True
+
logger_data["payload"] = payload
with metrics.timer(op):
diff --git a/src/sentry/options/defaults.py b/src/sentry/options/defaults.py
index 165bec03772779..6864f38faf9ca1 100644
--- a/src/sentry/options/defaults.py
+++ b/src/sentry/options/defaults.py
@@ -722,6 +722,22 @@
flags=FLAG_AUTOMATOR_MODIFIABLE,
)
+# Enable sending the flag to the microservice to tell it to purposefully take longer than our
+# timeout, to see the effect on the overall error event processing backlog
+register(
+ "processing.severity-backlog-test.timeout",
+ default=False,
+ flags=FLAG_AUTOMATOR_MODIFIABLE,
+)
+
+# Enable sending the flag to the microservice to tell it to purposefully send back an error, to see
+# the effect on the overall error event processing backlog
+register(
+ "processing.severity-backlog-test.error",
+ default=False,
+ flags=FLAG_AUTOMATOR_MODIFIABLE,
+)
+
# ## sentry.killswitches
#
|
e028e5dcf70594110dceaad6e27e63277890f878
|
2023-09-21 06:10:22
|
Alex Zaslavsky
|
fix(backup): Fix backup tests for CustomDynamicSamplingRule (#56607)
| false
|
Fix backup tests for CustomDynamicSamplingRule (#56607)
|
fix
|
diff --git a/src/sentry/testutils/helpers/backups.py b/src/sentry/testutils/helpers/backups.py
index 680097379bb429..eec48918a7d008 100644
--- a/src/sentry/testutils/helpers/backups.py
+++ b/src/sentry/testutils/helpers/backups.py
@@ -46,6 +46,7 @@
DashboardWidgetQuery,
DashboardWidgetTypes,
)
+from sentry.models.dynamicsampling import CustomDynamicSamplingRule
from sentry.models.integrations.integration import Integration
from sentry.models.integrations.organization_integration import OrganizationIntegration
from sentry.models.integrations.project_integration import ProjectIntegration
@@ -324,6 +325,15 @@ def create_exhaustive_organization(
sent_initial_email_date=datetime.now(),
sent_final_email_date=datetime.now(),
)
+ CustomDynamicSamplingRule.update_or_create(
+ condition={"op": "equals", "name": "environment", "value": "prod"},
+ start=timezone.now(),
+ end=timezone.now() + timedelta(hours=1),
+ project_ids=[project.id],
+ organization_id=org.id,
+ num_samples=100,
+ sample_rate=0.5,
+ )
# Environment*
self.create_environment(project=project)
diff --git a/tests/sentry/backup/test_models.py b/tests/sentry/backup/test_models.py
index 7d2e9eefbf1e5d..5f0af4b9e48b6e 100644
--- a/tests/sentry/backup/test_models.py
+++ b/tests/sentry/backup/test_models.py
@@ -228,6 +228,19 @@ def test_counter(self):
Counter.increment(project, 1)
return self.import_export_then_validate()
+ @targets(mark(CustomDynamicSamplingRule, CustomDynamicSamplingRuleProject))
+ def test_custom_dynamic_sampling(self):
+ CustomDynamicSamplingRule.update_or_create(
+ condition={"op": "equals", "name": "environment", "value": "prod"},
+ start=timezone.now(),
+ end=timezone.now() + timedelta(hours=1),
+ project_ids=[self.project.id],
+ organization_id=self.organization.id,
+ num_samples=100,
+ sample_rate=0.5,
+ )
+ return self.import_export_then_validate()
+
@targets(mark(Dashboard))
def test_dashboard(self):
self.create_dashboard()
@@ -526,25 +539,6 @@ def test_user_role(self):
UserRoleUser.objects.create(user=user, role=role)
return self.import_export_then_validate()
- @targets(mark(CustomDynamicSamplingRule, CustomDynamicSamplingRuleProject))
- def test_custom_dynamic_sampling_rule(self):
- condition = {"op": "equals", "name": "environment", "value": "prod"}
-
- rule = CustomDynamicSamplingRule.update_or_create(
- condition=condition,
- start=timezone.now(),
- end=timezone.now() + timedelta(hours=1),
- project_ids=[self.project.id],
- organization_id=self.organization.id,
- num_samples=100,
- sample_rate=0.5,
- )
-
- CustomDynamicSamplingRuleProject.objects.create(
- rule=rule, project=self.project, organization=self.organization
- )
- return self.import_export_then_validate()
-
@run_backup_tests_only_on_single_db
class DynamicRelocationScopeTests(TransactionTestCase):
|
0d3b38345b5e396ec835d31a0c5ce38e786fa788
|
2020-09-15 02:36:51
|
Evan Purkhiser
|
ref(py3): Fix sourcemap URL discovery in py3 (#20677)
| false
|
Fix sourcemap URL discovery in py3 (#20677)
|
ref
|
diff --git a/src/sentry/lang/javascript/processor.py b/src/sentry/lang/javascript/processor.py
index c5a82883e588e3..4e903677e13a87 100644
--- a/src/sentry/lang/javascript/processor.py
+++ b/src/sentry/lang/javascript/processor.py
@@ -1,5 +1,7 @@
from __future__ import absolute_import, print_function
+from django.utils.encoding import force_text, force_bytes
+
__all__ = ["JavaScriptStacktraceProcessor"]
import logging
@@ -64,7 +66,7 @@ class ZeroReturnError(Exception):
)
VERSION_RE = re.compile(r"^[a-f0-9]{32}|[a-f0-9]{40}$", re.I)
NODE_MODULES_RE = re.compile(r"\bnode_modules/")
-SOURCE_MAPPING_URL_RE = re.compile(r"\/\/# sourceMappingURL=(.*)$")
+SOURCE_MAPPING_URL_RE = re.compile(b"//# sourceMappingURL=(.*)$")
CACHE_CONTROL_RE = re.compile(r"max-age=(\d+)")
CACHE_CONTROL_MAX = 7200
CACHE_CONTROL_MIN = 60
@@ -152,8 +154,11 @@ def discover_sourcemap(result):
# all keys become lowercase so they're normalized
sourcemap = result.headers.get("sourcemap", result.headers.get("x-sourcemap"))
+ # Force the header value to bytes since we'll be manipulating bytes here
+ sourcemap = force_bytes(sourcemap) if sourcemap is not None else None
+
if not sourcemap:
- parsed_body = result.body.split("\n")
+ parsed_body = result.body.split(b"\n")
# Source maps are only going to exist at either the top or bottom of the document.
# Technically, there isn't anything indicating *where* it should exist, so we
# are generous and assume it's somewhere either in the first or last 5 lines.
@@ -166,7 +171,7 @@ def discover_sourcemap(result):
# We want to scan each line sequentially, and the last one found wins
# This behavior is undocumented, but matches what Chrome and Firefox do.
for line in possibilities:
- if line[:21] in ("//# sourceMappingURL=", "//@ sourceMappingURL="):
+ if line[:21] in (b"//# sourceMappingURL=", b"//@ sourceMappingURL="):
# We want everything AFTER the indicator, which is 21 chars long
sourcemap = line[21:].rstrip()
@@ -191,8 +196,8 @@ def discover_sourcemap(result):
# This comment is completely out of spec and no browser
# would support this, but we need to strip it to make
# people happy.
- if "/*" in sourcemap and sourcemap[-2:] == "*/":
- index = sourcemap.index("/*")
+ if b"/*" in sourcemap and sourcemap[-2:] == b"*/":
+ index = sourcemap.index(b"/*")
# comment definitely shouldn't be the first character,
# so let's just make sure of that.
if index == 0:
@@ -201,9 +206,9 @@ def discover_sourcemap(result):
)
sourcemap = sourcemap[:index]
# fix url so its absolute
- sourcemap = non_standard_url_join(result.url, sourcemap)
+ sourcemap = non_standard_url_join(result.url, force_text(sourcemap))
- return sourcemap
+ return force_text(sourcemap) if sourcemap is not None else None
def fetch_release_file(filename, release, dist=None):
@@ -417,7 +422,8 @@ def fetch_sourcemap(url, project=None, release=None, dist=None, allow_scraping=T
if is_data_uri(url):
try:
body = base64.b64decode(
- url[BASE64_PREAMBLE_LENGTH:] + (b"=" * (-(len(url) - BASE64_PREAMBLE_LENGTH) % 4))
+ force_bytes(url[BASE64_PREAMBLE_LENGTH:])
+ + (b"=" * (-(len(url) - BASE64_PREAMBLE_LENGTH) % 4))
)
except TypeError as e:
raise UnparseableSourcemap({"url": "<base64>", "reason": six.text_type(e)})
diff --git a/tests/sentry/lang/javascript/test_processor.py b/tests/sentry/lang/javascript/test_processor.py
index fb0f0bf4f70c71..6471970cbc643a 100644
--- a/tests/sentry/lang/javascript/test_processor.py
+++ b/tests/sentry/lang/javascript/test_processor.py
@@ -133,7 +133,7 @@ def test_distribution(self):
assert isinstance(foo_result.body, six.binary_type)
assert foo_result == http.UrlResult(
- "file.min.js", {"content-type": "application/json; charset=utf-8"}, "foo", 200, "utf-8"
+ "file.min.js", {"content-type": "application/json; charset=utf-8"}, b"foo", 200, "utf-8"
)
# test that cache pays attention to dist value as well as name
@@ -142,7 +142,7 @@ def test_distribution(self):
# result is cached, but that's not what we should find
assert bar_result != foo_result
assert bar_result == http.UrlResult(
- "file.min.js", {"content-type": "application/json; charset=utf-8"}, "bar", 200, "utf-8"
+ "file.min.js", {"content-type": "application/json; charset=utf-8"}, b"bar", 200, "utf-8"
)
def test_tilde(self):
@@ -293,7 +293,7 @@ def test_non_url_without_release(self):
@patch("sentry.lang.javascript.processor.fetch_release_file")
def test_non_url_with_release(self, mock_fetch_release_file):
mock_fetch_release_file.return_value = http.UrlResult(
- "/example.js", {"content-type": "application/json"}, "foo", 200, None
+ "/example.js", {"content-type": "application/json"}, b"foo", 200, None
)
release = Release.objects.create(version="1", organization_id=self.project.organization_id)
@@ -396,23 +396,27 @@ def test_valid_input(self):
class DiscoverSourcemapTest(unittest.TestCase):
# discover_sourcemap(result)
def test_simple(self):
- result = http.UrlResult("http://example.com", {}, "", 200, None)
+ result = http.UrlResult("http://example.com", {}, b"", 200, None)
assert discover_sourcemap(result) is None
result = http.UrlResult(
- "http://example.com", {"x-sourcemap": "http://example.com/source.map.js"}, "", 200, None
+ "http://example.com",
+ {"x-sourcemap": "http://example.com/source.map.js"},
+ b"",
+ 200,
+ None,
)
assert discover_sourcemap(result) == "http://example.com/source.map.js"
result = http.UrlResult(
- "http://example.com", {"sourcemap": "http://example.com/source.map.js"}, "", 200, None
+ "http://example.com", {"sourcemap": "http://example.com/source.map.js"}, b"", 200, None
)
assert discover_sourcemap(result) == "http://example.com/source.map.js"
result = http.UrlResult(
"http://example.com",
{},
- "//@ sourceMappingURL=http://example.com/source.map.js\nconsole.log(true)",
+ b"//@ sourceMappingURL=http://example.com/source.map.js\nconsole.log(true)",
200,
None,
)
@@ -421,7 +425,7 @@ def test_simple(self):
result = http.UrlResult(
"http://example.com",
{},
- "//# sourceMappingURL=http://example.com/source.map.js\nconsole.log(true)",
+ b"//# sourceMappingURL=http://example.com/source.map.js\nconsole.log(true)",
200,
None,
)
@@ -430,7 +434,7 @@ def test_simple(self):
result = http.UrlResult(
"http://example.com",
{},
- "console.log(true)\n//@ sourceMappingURL=http://example.com/source.map.js",
+ b"console.log(true)\n//@ sourceMappingURL=http://example.com/source.map.js",
200,
None,
)
@@ -439,7 +443,7 @@ def test_simple(self):
result = http.UrlResult(
"http://example.com",
{},
- "console.log(true)\n//# sourceMappingURL=http://example.com/source.map.js",
+ b"console.log(true)\n//# sourceMappingURL=http://example.com/source.map.js",
200,
None,
)
@@ -448,7 +452,7 @@ def test_simple(self):
result = http.UrlResult(
"http://example.com",
{},
- "console.log(true)\n//# sourceMappingURL=http://example.com/source.map.js\n//# sourceMappingURL=http://example.com/source2.map.js",
+ b"console.log(true)\n//# sourceMappingURL=http://example.com/source.map.js\n//# sourceMappingURL=http://example.com/source2.map.js",
200,
None,
)
@@ -458,18 +462,20 @@ def test_simple(self):
result = http.UrlResult(
"http://example.com",
{},
- "console.log(true);//# sourceMappingURL=http://example.com/source.map.js",
+ b"console.log(true);//# sourceMappingURL=http://example.com/source.map.js",
200,
None,
)
assert discover_sourcemap(result) == "http://example.com/source.map.js"
result = http.UrlResult(
- "http://example.com", {}, "//# sourceMappingURL=app.map.js/*ascii:lol*/", 200, None
+ "http://example.com", {}, b"//# sourceMappingURL=app.map.js/*ascii:lol*/", 200, None
)
assert discover_sourcemap(result) == "http://example.com/app.map.js"
- result = http.UrlResult("http://example.com", {}, "//# sourceMappingURL=/*lol*/", 200, None)
+ result = http.UrlResult(
+ "http://example.com", {}, b"//# sourceMappingURL=/*lol*/", 200, None
+ )
with self.assertRaises(AssertionError):
discover_sourcemap(result)
|
6113472f8aee7539d6656cfa1272bbcd8e5ddac7
|
2024-03-19 21:39:18
|
Abdkhan14
|
feat(new-trace): Added node path to url for when event id link has sp… (#67138)
| false
|
Added node path to url for when event id link has sp… (#67138)
|
feat
|
diff --git a/static/app/views/performance/newTraceDetails/trace.tsx b/static/app/views/performance/newTraceDetails/trace.tsx
index 272d22d52b1a1d..298d73dd75dbf8 100644
--- a/static/app/views/performance/newTraceDetails/trace.tsx
+++ b/static/app/views/performance/newTraceDetails/trace.tsx
@@ -203,6 +203,7 @@ function Trace({
manager.initializeTraceSpace([trace.root.space[0], 0, trace.root.space[1], 1]);
const maybeQueue = decodeScrollQueue(qs.parse(location.search).node);
const maybeEventId = qs.parse(location.search)?.eventId;
+
if (maybeQueue || maybeEventId) {
scrollQueueRef.current = {
eventId: maybeEventId as string,
@@ -229,20 +230,21 @@ function Trace({
return;
}
- const promise = scrollQueueRef.current?.eventId
- ? manager.scrollToEventID(
- scrollQueueRef?.current?.eventId,
+ // Node path has higher specificity than eventId
+ const promise = scrollQueueRef.current?.path
+ ? manager.scrollToPath(
trace,
+ scrollQueueRef.current.path,
() => setRender(a => (a + 1) % 2),
{
api,
organization,
}
)
- : scrollQueueRef?.current?.path
- ? manager.scrollToPath(
+ : scrollQueueRef.current.eventId
+ ? manager.scrollToEventID(
+ scrollQueueRef?.current?.eventId,
trace,
- scrollQueueRef.current.path,
() => setRender(a => (a + 1) % 2),
{
api,
diff --git a/static/app/views/performance/traceDetails/TraceDetailsRouting.tsx b/static/app/views/performance/traceDetails/TraceDetailsRouting.tsx
index 326bb5cd1502b8..a39415f42b3087 100644
--- a/static/app/views/performance/traceDetails/TraceDetailsRouting.tsx
+++ b/static/app/views/performance/traceDetails/TraceDetailsRouting.tsx
@@ -41,9 +41,21 @@ function TraceDetailsRouting(props: Props) {
event.eventID
);
+ const query = {...traceDetailsLocation.query};
+ if (location.hash.includes('span')) {
+ const spanHashValue = location.hash
+ .split('#')
+ .filter(value => value.includes('span'))[0];
+ const spanId = spanHashValue.split('-')[1];
+
+ if (spanId) {
+ query.node = [`span:${spanId}`, `txn:${event.eventID}`];
+ }
+ }
+
browserHistory.replace({
pathname: traceDetailsLocation.pathname,
- query: traceDetailsLocation.query,
+ query,
});
}
}
|
79a804eaeb4839dca7e16d698d773017f0f3db70
|
2024-06-17 19:05:53
|
anthony sottile
|
ref: reset_options only supports project (#72815)
| false
|
reset_options only supports project (#72815)
|
ref
|
diff --git a/src/sentry/plugins/base/v1.py b/src/sentry/plugins/base/v1.py
index 073eaf458b4160..9487bdd0f30c0b 100644
--- a/src/sentry/plugins/base/v1.py
+++ b/src/sentry/plugins/base/v1.py
@@ -117,10 +117,10 @@ def is_enabled(self, project: Project | RpcProject | None = None):
return True
- def reset_options(self, project=None, user=None):
+ def reset_options(self, project=None):
from sentry.plugins.helpers import reset_options
- return reset_options(self.get_conf_key(), project, user)
+ return reset_options(self.get_conf_key(), project)
def get_option(self, key, project=None, user=None):
"""
diff --git a/src/sentry/plugins/base/v2.py b/src/sentry/plugins/base/v2.py
index 3b2df6bc59a2f3..7b1f2349252f46 100644
--- a/src/sentry/plugins/base/v2.py
+++ b/src/sentry/plugins/base/v2.py
@@ -119,10 +119,10 @@ def is_hidden(self):
"""
return self.slug in HIDDEN_PLUGINS
- def reset_options(self, project=None, user=None):
+ def reset_options(self, project=None):
from sentry.plugins.helpers import reset_options
- return reset_options(self.get_conf_key(), project, user)
+ return reset_options(self.get_conf_key(), project)
def get_option(self, key, project=None, user=None):
"""
diff --git a/src/sentry/plugins/helpers.py b/src/sentry/plugins/helpers.py
index 42b7b958190cfc..7a4c902434159a 100644
--- a/src/sentry/plugins/helpers.py
+++ b/src/sentry/plugins/helpers.py
@@ -9,13 +9,8 @@
__all__ = ("set_option", "get_option", "unset_option")
-def reset_options(prefix, project=None, user=None):
- if user:
- UserOption.objects.filter(
- key__startswith=f"{prefix}:", project_id=project.id if project else None, user=user
- ).delete()
- UserOption.objects.clear_cache()
- elif project:
+def reset_options(prefix, project=None):
+ if project:
ProjectOption.objects.filter(key__startswith=f"{prefix}:", project=project).delete()
ProjectOption.objects.clear_local_cache()
else:
diff --git a/src/sentry_plugins/sessionstack/plugin.py b/src/sentry_plugins/sessionstack/plugin.py
index d634f8af9465f6..6b00a3062d7783 100644
--- a/src/sentry_plugins/sessionstack/plugin.py
+++ b/src/sentry_plugins/sessionstack/plugin.py
@@ -59,7 +59,7 @@ def has_project_conf(self):
def get_custom_contexts(self):
return [SessionStackContextType]
- def reset_options(self, project=None, user=None):
+ def reset_options(self, project=None):
self.disable(project)
self.set_option("account_email", "", project)
|
14d89512b42e45ecee090831563644e08824f761
|
2020-07-15 22:57:34
|
Scott Cooper
|
ref(ts): Convert textarea to typescript (#19835)
| false
|
Convert textarea to typescript (#19835)
|
ref
|
diff --git a/package.json b/package.json
index 7ae7c39ebe900e..89b224b8ecc82e 100644
--- a/package.json
+++ b/package.json
@@ -98,7 +98,7 @@
"prop-types": "^15.6.0",
"query-string": "6.6.0",
"react": "16.12.0",
- "react-autosize-textarea": "^4.0.0",
+ "react-autosize-textarea": "7.1.0",
"react-bootstrap": "^0.32.0",
"react-date-range": "^1.0.0-beta",
"react-document-title": "2.0.3",
diff --git a/src/sentry/static/sentry/app/views/settings/components/forms/controls/textarea.jsx b/src/sentry/static/sentry/app/views/settings/components/forms/controls/textarea.jsx
deleted file mode 100644
index 3fc84d4aad1d23..00000000000000
--- a/src/sentry/static/sentry/app/views/settings/components/forms/controls/textarea.jsx
+++ /dev/null
@@ -1,38 +0,0 @@
-import PropTypes from 'prop-types';
-import React from 'react';
-import TextareaAutosize from 'react-autosize-textarea';
-import styled from '@emotion/styled';
-import isPropValid from '@emotion/is-prop-valid';
-
-import {inputStyles} from 'app/styles/input';
-
-const TextAreaControl = React.forwardRef(({autosize, rows, ...p}, ref) =>
- autosize ? (
- <TextareaAutosize async ref={ref} rows={rows ? rows : 2} {...p} />
- ) : (
- <textarea ref={ref} {...p} />
- )
-);
-
-TextAreaControl.propTypes = {
- /**
- * Enable autosizing of the textarea.
- */
- autosize: PropTypes.bool,
- /**
- * Number of rows to default to.
- */
- rows: PropTypes.number,
- /**
- * Requests monospace input
- */
- monospace: PropTypes.bool,
-};
-
-const propFilter = p => ['autosize', 'rows', 'maxRows'].includes(p) || isPropValid(p);
-
-const TextArea = styled(TextAreaControl, {shouldForwardProp: propFilter})`
- ${inputStyles};
-`;
-
-export default TextArea;
diff --git a/src/sentry/static/sentry/app/views/settings/components/forms/controls/textarea.tsx b/src/sentry/static/sentry/app/views/settings/components/forms/controls/textarea.tsx
new file mode 100644
index 00000000000000..a84f587544e8d1
--- /dev/null
+++ b/src/sentry/static/sentry/app/views/settings/components/forms/controls/textarea.tsx
@@ -0,0 +1,48 @@
+import PropTypes from 'prop-types';
+import React from 'react';
+import TextareaAutosize from 'react-autosize-textarea';
+import styled from '@emotion/styled';
+import isPropValid from '@emotion/is-prop-valid';
+
+import {inputStyles} from 'app/styles/input';
+
+type InputProps = Omit<Parameters<typeof inputStyles>[0], 'theme'>;
+type Props = React.TextareaHTMLAttributes<HTMLTextAreaElement> &
+ InputProps & {
+ /**
+ * Enable autosizing of the textarea.
+ */
+ autosize?: boolean;
+ /**
+ * Number of rows to default to.
+ */
+ rows?: number;
+ };
+
+const TextAreaControl = React.forwardRef(function TextAreaControl(
+ {autosize, rows, ...p}: Props,
+ ref: React.Ref<HTMLTextAreaElement>
+) {
+ return autosize ? (
+ <TextareaAutosize async ref={ref} rows={rows ? rows : 2} {...p} />
+ ) : (
+ <textarea ref={ref} {...p} />
+ );
+});
+
+TextAreaControl.displayName = 'TextAreaControl';
+
+TextAreaControl.propTypes = {
+ autosize: PropTypes.bool,
+ rows: PropTypes.number,
+ monospace: PropTypes.bool,
+};
+
+const propFilter = (p: string) =>
+ ['autosize', 'rows', 'maxRows'].includes(p) || isPropValid(p);
+
+const TextArea = styled(TextAreaControl, {shouldForwardProp: propFilter})`
+ ${inputStyles};
+`;
+
+export default TextArea;
diff --git a/src/sentry/static/sentry/app/views/settings/organizationRelays/modals/form.tsx b/src/sentry/static/sentry/app/views/settings/organizationRelays/modals/form.tsx
index d305f4874cc9f0..2b73b4f749bb8f 100644
--- a/src/sentry/static/sentry/app/views/settings/organizationRelays/modals/form.tsx
+++ b/src/sentry/static/sentry/app/views/settings/organizationRelays/modals/form.tsx
@@ -24,7 +24,7 @@ type Props = {
const Form = ({values, onChange, errors, onValidate, disables, onValidateKey}: Props) => {
const handleChange = (field: FormField) => (
- event: React.ChangeEvent<HTMLInputElement>
+ event: React.ChangeEvent<HTMLTextAreaElement> | React.ChangeEvent<HTMLInputElement>
) => {
onChange(field, event.target.value);
};
diff --git a/tests/js/spec/components/group/__snapshots__/externalIssueForm.spec.jsx.snap b/tests/js/spec/components/group/__snapshots__/externalIssueForm.spec.jsx.snap
index 3517a5414114f9..34fa3f03e79ab3 100644
--- a/tests/js/spec/components/group/__snapshots__/externalIssueForm.spec.jsx.snap
+++ b/tests/js/spec/components/group/__snapshots__/externalIssueForm.spec.jsx.snap
@@ -4725,8 +4725,8 @@ exports[`ExternalIssueForm link renders 1`] = `
type="textarea"
value="Default Value"
>
- <ForwardRef
- className="css-u4op3m-TextArea e1oph3pe0"
+ <TextAreaControl
+ className="css-u4op3m-TextArea edis3zx0"
default="Default Value"
disabled={false}
id="comment"
@@ -4739,7 +4739,7 @@ exports[`ExternalIssueForm link renders 1`] = `
value="Default Value"
>
<textarea
- className="css-u4op3m-TextArea e1oph3pe0"
+ className="css-u4op3m-TextArea edis3zx0"
default="Default Value"
disabled={false}
id="comment"
@@ -4751,7 +4751,7 @@ exports[`ExternalIssueForm link renders 1`] = `
type="textarea"
value="Default Value"
/>
- </ForwardRef>
+ </TextAreaControl>
</TextArea>
</Observer>
</div>
diff --git a/tests/js/spec/views/__snapshots__/ownershipInput.spec.jsx.snap b/tests/js/spec/views/__snapshots__/ownershipInput.spec.jsx.snap
index bae3df54410e2e..09614ad62d9127 100644
--- a/tests/js/spec/views/__snapshots__/ownershipInput.spec.jsx.snap
+++ b/tests/js/spec/views/__snapshots__/ownershipInput.spec.jsx.snap
@@ -1213,7 +1213,6 @@ exports[`Project Ownership Input renders 1`] = `
}
>
<StyledTextArea
- async={false}
autoCapitalize="off"
autoComplete="off"
autoCorrect="off"
@@ -1222,12 +1221,10 @@ exports[`Project Ownership Input renders 1`] = `
path:src/example/pipeline/* [email protected] #infra
url:http://example.com/settings/* #product
tags.sku_class:enterprise #enterprise"
- rows={1}
spellCheck="false"
value="new"
>
- <TextareaAutosize
- async={false}
+ <ForwardRef
autoCapitalize="off"
autoComplete="off"
autoCorrect="off"
@@ -1237,16 +1234,16 @@ tags.sku_class:enterprise #enterprise"
path:src/example/pipeline/* [email protected] #infra
url:http://example.com/settings/* #product
tags.sku_class:enterprise #enterprise"
- rows={1}
spellCheck="false"
value="new"
>
- <textarea
+ <TextareaAutosizeClass
async={false}
autoCapitalize="off"
autoComplete="off"
autoCorrect="off"
className="css-1ws5ptf-StyledTextArea en3n9di3"
+ innerRef={null}
onChange={[Function]}
placeholder="#example usage
path:src/example/pipeline/* [email protected] #infra
@@ -1255,8 +1252,24 @@ tags.sku_class:enterprise #enterprise"
rows={1}
spellCheck="false"
value="new"
- />
- </TextareaAutosize>
+ >
+ <textarea
+ async={false}
+ autoCapitalize="off"
+ autoComplete="off"
+ autoCorrect="off"
+ className="css-1ws5ptf-StyledTextArea en3n9di3"
+ onChange={[Function]}
+ placeholder="#example usage
+path:src/example/pipeline/* [email protected] #infra
+url:http://example.com/settings/* #product
+tags.sku_class:enterprise #enterprise"
+ rows={1}
+ spellCheck="false"
+ value="new"
+ />
+ </TextareaAutosizeClass>
+ </ForwardRef>
</StyledTextArea>
<ActionBar>
<div
diff --git a/yarn.lock b/yarn.lock
index ebfaf260453cca..98a9bb832b666d 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -4018,7 +4018,7 @@ autoprefixer@^9.7.5:
postcss "^7.0.27"
postcss-value-parser "^4.0.3"
-autosize@^4.0.0:
+autosize@^4.0.2:
version "4.0.2"
resolved "https://registry.yarnpkg.com/autosize/-/autosize-4.0.2.tgz#073cfd07c8bf45da4b9fd153437f5bafbba1e4c9"
integrity sha512-jnSyH2d+qdfPGpWlcuhGiHmqBJ6g3X+8T+iRwFrHPLVcdoGJE/x6Qicm6aDHfTsbgZKxyV8UU/YB2p4cjKDRRA==
@@ -12680,12 +12680,12 @@ react-addons-create-fragment@^15.6.2:
loose-envify "^1.3.1"
object-assign "^4.1.0"
-react-autosize-textarea@^4.0.0:
- version "4.0.0"
- resolved "https://registry.yarnpkg.com/react-autosize-textarea/-/react-autosize-textarea-4.0.0.tgz#893d43606b1efe820c71476f25d141c6b25deaab"
- integrity sha512-QVLgrvLZIjWNX4o5cHcsJuIjVg7JCNyxzObcFb08PWepDImeKenJt3yhjruEBFyZZyWtPAb65OPKbF1v79MhvQ==
[email protected]:
+ version "7.1.0"
+ resolved "https://registry.yarnpkg.com/react-autosize-textarea/-/react-autosize-textarea-7.1.0.tgz#902c84fc395a689ca3a484dfb6bc2be9ba3694d1"
+ integrity sha512-BHpjCDkuOlllZn3nLazY2F8oYO1tS2jHnWhcjTWQdcKiiMU6gHLNt/fzmqMSyerR0eTdKtfSIqtSeTtghNwS+g==
dependencies:
- autosize "^4.0.0"
+ autosize "^4.0.2"
line-height "^0.3.1"
prop-types "^15.5.6"
|
262da126bab3daa8909fe75cbe9852c3136a7af4
|
2021-01-07 20:34:35
|
Priscila Oliveira
|
ref(inbox): Update Reprocessing tab display logic (#22891)
| false
|
Update Reprocessing tab display logic (#22891)
|
ref
|
diff --git a/src/sentry/static/sentry/app/components/stream/group.tsx b/src/sentry/static/sentry/app/components/stream/group.tsx
index 3a6adcbab41633..23eaa38b11df24 100644
--- a/src/sentry/static/sentry/app/components/stream/group.tsx
+++ b/src/sentry/static/sentry/app/components/stream/group.tsx
@@ -70,7 +70,7 @@ type Props = {
id: string;
selection: GlobalSelection;
organization: Organization;
- isReprocessingQuery?: boolean;
+ displayReprocessingLayout?: boolean;
query?: string;
hasGuideAnchor?: boolean;
memberList?: User[];
@@ -274,7 +274,7 @@ class StreamGroup extends React.Component<Props, State> {
statsPeriod,
selection,
organization,
- isReprocessingQuery,
+ displayReprocessingLayout,
} = this.props;
const {period, start, end} = selection.datetime || {};
@@ -297,13 +297,13 @@ class StreamGroup extends React.Component<Props, State> {
return (
<Wrapper
data-test-id="group"
- onClick={isReprocessingQuery ? undefined : this.toggleSelect}
+ onClick={displayReprocessingLayout ? undefined : this.toggleSelect}
reviewed={reviewed}
hasInbox={hasInbox}
>
{canSelect && (
<GroupCheckBoxWrapper ml={2}>
- <GroupCheckBox id={data.id} disabled={!!isReprocessingQuery} />
+ <GroupCheckBox id={data.id} disabled={!!displayReprocessingLayout} />
</GroupCheckBoxWrapper>
)}
<GroupSummary
@@ -322,7 +322,7 @@ class StreamGroup extends React.Component<Props, State> {
<EventOrGroupExtraDetails organization={organization} data={data} />
</GroupSummary>
{hasGuideAnchor && <GuideAnchor target="issue_stream" />}
- {withChart && !isReprocessingQuery && (
+ {withChart && !displayReprocessingLayout && (
<ChartWrapper className="hidden-xs hidden-sm">
{!data.filtered?.stats && !data.stats ? (
<Placeholder height="24px" />
@@ -335,7 +335,7 @@ class StreamGroup extends React.Component<Props, State> {
)}
</ChartWrapper>
)}
- {isReprocessingQuery ? (
+ {displayReprocessingLayout ? (
this.renderReprocessingColumns()
) : (
<React.Fragment>
diff --git a/src/sentry/static/sentry/app/views/issueList/actions/index.tsx b/src/sentry/static/sentry/app/views/issueList/actions/index.tsx
index ddd3c055a3b7d0..d621001c21c3fd 100644
--- a/src/sentry/static/sentry/app/views/issueList/actions/index.tsx
+++ b/src/sentry/static/sentry/app/views/issueList/actions/index.tsx
@@ -13,8 +13,6 @@ import {GlobalSelection, Group, Organization} from 'app/types';
import {callIfFunction} from 'app/utils/callIfFunction';
import withApi from 'app/utils/withApi';
-import {Query} from '../utils';
-
import ActionSet from './actionSet';
import Headers from './headers';
import {BULK_LIMIT, BULK_LIMIT_STR, ConfirmAction} from './utils';
@@ -33,6 +31,7 @@ type Props = {
queryCount: number;
queryMaxCount: number;
pageCount: number;
+ displayReprocessingActions: boolean;
hasInbox?: boolean;
};
@@ -242,6 +241,7 @@ class IssueListActions extends React.Component<Props, State> {
queryMaxCount,
selection,
organization,
+ displayReprocessingActions,
} = this.props;
const {
@@ -254,8 +254,6 @@ class IssueListActions extends React.Component<Props, State> {
} = this.state;
const numIssues = issues.size;
- const isReprocessingQuery =
- query === Query.REPROCESSING && organization.features.includes('reprocessing-v2');
return (
<Sticky>
@@ -264,10 +262,10 @@ class IssueListActions extends React.Component<Props, State> {
<Checkbox
onChange={this.handleSelectAll}
checked={pageSelected}
- disabled={isReprocessingQuery}
+ disabled={displayReprocessingActions}
/>
</ActionsCheckbox>
- {(anySelected || !hasInbox) && !isReprocessingQuery && (
+ {(anySelected || !hasInbox) && !displayReprocessingActions && (
<ActionSet
orgSlug={organization.slug}
queryCount={queryCount}
@@ -295,7 +293,7 @@ class IssueListActions extends React.Component<Props, State> {
queryCount={queryCount}
queryMaxCount={queryMaxCount}
hasInbox={hasInbox}
- isReprocessingQuery={isReprocessingQuery}
+ isReprocessingQuery={displayReprocessingActions}
/>
)}
</StyledFlex>
diff --git a/src/sentry/static/sentry/app/views/issueList/header.tsx b/src/sentry/static/sentry/app/views/issueList/header.tsx
index 54e55bf53e5451..df41dbb3b48fda 100644
--- a/src/sentry/static/sentry/app/views/issueList/header.tsx
+++ b/src/sentry/static/sentry/app/views/issueList/header.tsx
@@ -29,6 +29,7 @@ type Props = {
projects: Array<Project>;
onRealtimeChange: (realtime: boolean) => void;
onTabChange: (query: string) => void;
+ displayReprocessingTab: boolean;
};
function IssueListHeader({
@@ -42,6 +43,7 @@ function IssueListHeader({
onRealtimeChange,
projects,
router,
+ displayReprocessingTab,
}: Props) {
const selectedProjectSlugs = projectIds
.map(projectId => projects.find(project => project.id === projectId)?.slug)
@@ -52,6 +54,10 @@ function IssueListHeader({
const tabs = getTabs(organization);
+ const visibleTabs = displayReprocessingTab
+ ? tabs
+ : tabs.filter(([tab]) => tab !== Query.REPROCESSING);
+
function handleSelectProject(settingsPage: string) {
return function (event: React.MouseEvent) {
event.preventDefault();
@@ -108,7 +114,7 @@ function IssueListHeader({
</BorderlessHeader>
<TabLayoutHeader>
<Layout.HeaderNavTabs underlined>
- {tabs.map(([tabQuery, {name: queryName}]) => (
+ {visibleTabs.map(([tabQuery, {name: queryName}]) => (
<li key={tabQuery} className={query === tabQuery ? 'active' : ''}>
<a onClick={() => onTabChange(tabQuery)}>
{queryName}{' '}
diff --git a/src/sentry/static/sentry/app/views/issueList/overview.tsx b/src/sentry/static/sentry/app/views/issueList/overview.tsx
index 801c30f6a42816..e159ce4aa78792 100644
--- a/src/sentry/static/sentry/app/views/issueList/overview.tsx
+++ b/src/sentry/static/sentry/app/views/issueList/overview.tsx
@@ -37,6 +37,7 @@ import space from 'app/styles/space';
import {
BaseGroup,
GlobalSelection,
+ Group,
Member,
Organization,
SavedSearch,
@@ -271,6 +272,7 @@ class IssueListOverview extends React.Component<Props, State> {
}
const {query} = location.query;
+
if (query !== undefined) {
return query as string;
}
@@ -414,6 +416,7 @@ class IssueListOverview extends React.Component<Props, State> {
if (!requestParams.statsPeriod && !requestParams.start) {
requestParams.statsPeriod = DEFAULT_STATS_PERIOD;
}
+
try {
const response = await this.props.api.requestPromise(
this.getGroupCountsEndpoint(),
@@ -422,6 +425,7 @@ class IssueListOverview extends React.Component<Props, State> {
data: qs.stringify(requestParams),
}
);
+
// Counts coming from the counts endpoint is limited to 100, for >= 100 we display 99+
queryCounts = {
...queryCounts,
@@ -616,7 +620,7 @@ class IssueListOverview extends React.Component<Props, State> {
listener = GroupStore.listen(() => this.onGroupChange(), undefined);
onGroupChange() {
- const groupIds = this._streamManager.getAllItems().map(item => item.id);
+ const groupIds = this._streamManager.getAllItems().map(item => item.id) ?? [];
if (!isEqual(groupIds, this.state.groupIds)) {
this.setState({groupIds});
}
@@ -726,22 +730,39 @@ class IssueListOverview extends React.Component<Props, State> {
}
};
+ displayReprocessingTab() {
+ const {organization} = this.props;
+ const {queryCounts} = this.state;
+
+ return (
+ organization.features.includes('reprocessing-v2') &&
+ !!queryCounts?.[Query.REPROCESSING]?.count
+ );
+ }
+
+ displayReprocessingLayout(showReprocessingTab: boolean, query: string) {
+ return showReprocessingTab && query === Query.REPROCESSING;
+ }
+
renderGroupNodes = (ids: string[], groupStatsPeriod: string) => {
const topIssue = ids[0];
const {memberList} = this.state;
- const {organization} = this.props;
const query = this.getQuery();
- const isReprocessingQuery =
- query === Query.REPROCESSING && organization.features.includes('reprocessing-v2');
return ids.map(id => {
const hasGuideAnchor = id === topIssue;
- const group = GroupStore.get(id);
+ const group = GroupStore.get(id) as Group | undefined;
let members: Member['user'][] | undefined;
- if (group && group.project) {
+ if (group?.project) {
members = memberList[group.project.slug];
}
+ const showReprocessingTab = this.displayReprocessingTab();
+ const displayReprocessingLayout = this.displayReprocessingLayout(
+ showReprocessingTab,
+ query
+ );
+
return (
<StreamGroup
key={id}
@@ -750,7 +771,7 @@ class IssueListOverview extends React.Component<Props, State> {
query={query}
hasGuideAnchor={hasGuideAnchor}
memberList={members}
- isReprocessingQuery={isReprocessingQuery}
+ displayReprocessingLayout={displayReprocessingLayout}
useFilteredStats
/>
);
@@ -863,7 +884,7 @@ class IssueListOverview extends React.Component<Props, State> {
const query = this.getQuery();
const queryPageInt = parseInt(location.query.page, 10);
const page = isNaN(queryPageInt) ? 0 : queryPageInt;
- const pageCount = page * MAX_ITEMS + groupIds?.length;
+ const pageCount = page * MAX_ITEMS + groupIds.length;
// TODO(workflow): When organization:inbox flag is removed add 'inbox' to tagStore
if (
@@ -876,6 +897,12 @@ class IssueListOverview extends React.Component<Props, State> {
const projectIds = selection?.projects?.map(p => p.toString());
const orgSlug = organization.slug;
+ const showReprocessingTab = this.displayReprocessingTab();
+ const displayReprocessingActions = this.displayReprocessingLayout(
+ showReprocessingTab,
+ query
+ );
+
return (
<Feature organization={organization} features={['organizations:inbox']}>
{({hasFeature}) => (
@@ -891,6 +918,7 @@ class IssueListOverview extends React.Component<Props, State> {
projectIds={projectIds}
orgSlug={orgSlug}
router={router}
+ displayReprocessingTab={showReprocessingTab}
/>
)}
<StyledPageContent isInbox={hasFeature}>
@@ -928,6 +956,7 @@ class IssueListOverview extends React.Component<Props, State> {
groupIds={groupIds}
allResultsVisible={this.allResultsVisible()}
hasInbox={hasFeature}
+ displayReprocessingActions={displayReprocessingActions}
/>
<PanelBody>
<ProcessingIssueList
diff --git a/src/sentry/static/sentry/app/views/issueList/utils.tsx b/src/sentry/static/sentry/app/views/issueList/utils.tsx
index 65bdc3f91deb50..b1a635e8d70a85 100644
--- a/src/sentry/static/sentry/app/views/issueList/utils.tsx
+++ b/src/sentry/static/sentry/app/views/issueList/utils.tsx
@@ -58,7 +58,7 @@ export function getTabs(organization: Organization) {
Query.REPROCESSING,
{
name: t('Reprocessing'),
- count: false,
+ count: true,
enabled: organization.features.includes('reprocessing-v2'),
},
],
@@ -82,4 +82,5 @@ type QueryCount = {
count: number;
hasMore: boolean;
};
+
export type QueryCounts = Partial<Record<Query, QueryCount>>;
diff --git a/src/sentry/static/sentry/app/views/organizationGroupDetails/actions/index.tsx b/src/sentry/static/sentry/app/views/organizationGroupDetails/actions/index.tsx
index 074cc6a0952844..6b3b6f944e1f59 100644
--- a/src/sentry/static/sentry/app/views/organizationGroupDetails/actions/index.tsx
+++ b/src/sentry/static/sentry/app/views/organizationGroupDetails/actions/index.tsx
@@ -138,7 +138,7 @@ class Actions extends React.Component<Props, State> {
openModal(({closeModal, Header, Body}) => (
<ReprocessingDialogForm
group={group}
- orgSlug={organization.slug}
+ organization={organization}
project={project}
closeModal={closeModal}
Header={Header}
diff --git a/src/sentry/static/sentry/app/views/organizationGroupDetails/groupEventDetails/groupEventDetails.tsx b/src/sentry/static/sentry/app/views/organizationGroupDetails/groupEventDetails/groupEventDetails.tsx
index cf272427812f3c..41570d759d6a7d 100644
--- a/src/sentry/static/sentry/app/views/organizationGroupDetails/groupEventDetails/groupEventDetails.tsx
+++ b/src/sentry/static/sentry/app/views/organizationGroupDetails/groupEventDetails/groupEventDetails.tsx
@@ -222,7 +222,7 @@ class GroupEventDetails extends React.Component<Props, State> {
const eventWithMeta = withMeta(event) as Event;
// reprocessing
- const hasReprocessingV2Feature = project.features?.includes('reprocessing-v2');
+ const hasReprocessingV2Feature = organization.features?.includes('reprocessing-v2');
const {activity: activities, count} = group;
const groupCount = Number(count);
const mostRecentActivity = getGroupMostRecentActivity(activities);
diff --git a/src/sentry/static/sentry/app/views/organizationGroupDetails/reprocessingDialogForm.tsx b/src/sentry/static/sentry/app/views/organizationGroupDetails/reprocessingDialogForm.tsx
index 07b9bc6b4553a8..de7d21ac3f39d0 100644
--- a/src/sentry/static/sentry/app/views/organizationGroupDetails/reprocessingDialogForm.tsx
+++ b/src/sentry/static/sentry/app/views/organizationGroupDetails/reprocessingDialogForm.tsx
@@ -33,22 +33,16 @@ const impacts = [
type Props = Pick<ModalRenderProps, 'Header' | 'Body' | 'closeModal'> & {
group: Group;
project: Project;
- orgSlug: Organization['slug'];
+ organization: Organization;
};
-function ReprocessingDialogForm({
- orgSlug,
- group,
- project,
- Header,
- Body,
- closeModal,
-}: Props) {
+function ReprocessingDialogForm({group, organization, Header, Body, closeModal}: Props) {
+ const orgSlug = organization.slug;
const endpoint = `/organizations/${orgSlug}/issues/${group.id}/reprocessing/`;
const title = t('Reprocess Events');
function handleSuccess() {
- const hasReprocessingV2Feature = !!project.features?.includes('reprocessing-v2');
+ const hasReprocessingV2Feature = !!organization.features?.includes('reprocessing-v2');
if (hasReprocessingV2Feature) {
closeModal();
diff --git a/tests/js/spec/views/issueList/header.spec.jsx b/tests/js/spec/views/issueList/header.spec.jsx
index fd5ebb74432f8b..dd88908a0729e7 100644
--- a/tests/js/spec/views/issueList/header.spec.jsx
+++ b/tests/js/spec/views/issueList/header.spec.jsx
@@ -21,6 +21,10 @@ const queryCounts = {
count: 0,
hasMore: false,
},
+ 'is:reprocessing': {
+ count: 0,
+ hasMore: false,
+ },
};
const queryCountsMaxed = {
@@ -75,11 +79,18 @@ describe('IssueListHeader', () => {
<IssueListHeader
organization={organization}
query=""
- queryCounts={queryCounts}
+ queryCounts={{
+ ...queryCounts,
+ 'is:reprocessing': {
+ count: 1,
+ hasMore: false,
+ },
+ }}
+ displayReprocessingTab
projectIds={[]}
/>
);
- expect(wrapper.find('li').at(3).text()).toBe('Reprocessing ');
+ expect(wrapper.find('li').at(3).text()).toBe('Reprocessing 1');
});
it("renders all tabs inactive when query doesn't match", () => {
|
c4eecd40836100ac7c9b5334233267fb1b868719
|
2020-11-12 07:21:24
|
Evan Purkhiser
|
ref(py3): Handle ThreadedExecutor submission ordering (#21960)
| false
|
Handle ThreadedExecutor submission ordering (#21960)
|
ref
|
diff --git a/src/sentry/utils/concurrent.py b/src/sentry/utils/concurrent.py
index 5b6fbfd4637bbc..2e093892118384 100644
--- a/src/sentry/utils/concurrent.py
+++ b/src/sentry/utils/concurrent.py
@@ -4,6 +4,8 @@
import sys
import threading
import six
+import collections
+import functools
from six.moves.queue import Full, PriorityQueue
from concurrent.futures import Future
@@ -40,6 +42,15 @@ def run():
return future
[email protected]_ordering
+class PriorityTask(collections.namedtuple("PriorityTask", "priority item")):
+ def __eq__(self, b):
+ return self.priority == b.priority
+
+ def __lt__(self, b):
+ return self.priority < b.priority
+
+
class TimedFuture(Future):
def __init__(self, *args, **kwargs):
self.__timing = [None, None] # [started, finished/cancelled]
@@ -234,7 +245,7 @@ def submit(self, callable, priority=0, block=True, timeout=None):
self.start()
future = self.Future()
- task = (priority, (callable, future))
+ task = PriorityTask(priority, (callable, future))
try:
self.__queue.put(task, block=block, timeout=timeout)
except Full as error:
diff --git a/tests/sentry/utils/test_concurrent.py b/tests/sentry/utils/test_concurrent.py
index bc2588ca68f23e..91f739c5e686bf 100644
--- a/tests/sentry/utils/test_concurrent.py
+++ b/tests/sentry/utils/test_concurrent.py
@@ -171,6 +171,17 @@ def callable():
assert False, "expected future to raise"
+def test_threaded_same_priority_Tasks():
+ executor = ThreadedExecutor(worker_count=1)
+
+ def callable():
+ pass
+
+ # Test that we can correctly submit multiple tasks
+ executor.submit(callable)
+ executor.submit(callable)
+
+
def test_threaded_executor():
executor = ThreadedExecutor(worker_count=1, maxsize=3)
|
2211e9159c4d031428069f3772529b755f25e0cd
|
2024-05-21 04:13:30
|
volokluev
|
fix(filestore): add rate limit to event attachments (#71079)
| false
|
add rate limit to event attachments (#71079)
|
fix
|
diff --git a/src/sentry/event_manager.py b/src/sentry/event_manager.py
index 6b4724b8e674be..e239e0907ce97a 100644
--- a/src/sentry/event_manager.py
+++ b/src/sentry/event_manager.py
@@ -2772,36 +2772,57 @@ def save_attachment(
logger.exception("Missing chunks for cache_key=%s", cache_key)
return
+ from sentry import ratelimits as ratelimiter
- file = EventAttachment.putfile(project.id, attachment)
-
- EventAttachment.objects.create(
- # lookup:
- project_id=project.id,
- group_id=group_id,
- event_id=event_id,
- # metadata:
- type=attachment.type,
- name=attachment.name,
- content_type=file.content_type,
- size=file.size,
- sha1=file.sha1,
- # storage:
- file_id=file.file_id,
- blob_path=file.blob_path,
+ is_limited, num_requests, reset_time = ratelimiter.backend.is_limited_with_value(
+ key="event_attachment.save",
+ limit=options.get("sentry.save-event-attachments.project-per-5-minute-limit"),
+ project=project,
+ window=5 * 60,
)
+ if is_limited:
+ metrics.incr("event_manager.attachments.rate_limited")
+ track_outcome(
+ org_id=project.organization_id,
+ project_id=project.id,
+ key_id=key_id,
+ outcome=Outcome.RATE_LIMITED,
+ reason="Too many attachments ({num_requests}} uploaded in a 5 minute window, will reset at {reset_time}",
+ timestamp=timestamp,
+ event_id=event_id,
+ category=DataCategory.ATTACHMENT,
+ quantity=attachment.size or 1,
+ )
+ else:
+ file = EventAttachment.putfile(project.id, attachment)
- track_outcome(
- org_id=project.organization_id,
- project_id=project.id,
- key_id=key_id,
- outcome=Outcome.ACCEPTED,
- reason=None,
- timestamp=timestamp,
- event_id=event_id,
- category=DataCategory.ATTACHMENT,
- quantity=attachment.size or 1,
- )
+ EventAttachment.objects.create(
+ # lookup:
+ project_id=project.id,
+ group_id=group_id,
+ event_id=event_id,
+ # metadata:
+ type=attachment.type,
+ name=attachment.name,
+ content_type=file.content_type,
+ size=file.size,
+ sha1=file.sha1,
+ # storage:
+ file_id=file.file_id,
+ blob_path=file.blob_path,
+ )
+
+ track_outcome(
+ org_id=project.organization_id,
+ project_id=project.id,
+ key_id=key_id,
+ outcome=Outcome.ACCEPTED,
+ reason=None,
+ timestamp=timestamp,
+ event_id=event_id,
+ category=DataCategory.ATTACHMENT,
+ quantity=attachment.size or 1,
+ )
def save_attachments(cache_key: str | None, attachments: list[Attachment], job: Job) -> None:
diff --git a/src/sentry/options/defaults.py b/src/sentry/options/defaults.py
index 07f7fb6cb287ec..32240a7b09810c 100644
--- a/src/sentry/options/defaults.py
+++ b/src/sentry/options/defaults.py
@@ -2529,6 +2529,14 @@
"api.organization-activity.brownout-duration", default="PT1M", flags=FLAG_AUTOMATOR_MODIFIABLE
)
+
+register(
+ "sentry.save-event-attachments.project-per-5-minute-limit",
+ type=Int,
+ default=20000000,
+ flags=FLAG_AUTOMATOR_MODIFIABLE,
+)
+
# Enable percentile operations in the metrics/meta endpoint in the Metrics API for the orgs in the list. This is used to
# also hide those expensive operations from view in the Metrics UI for everyone except the whitelist.
register(
|
a21ad4354319ff0a8abb74b7c9870c5445a2bbb7
|
2023-08-17 17:56:23
|
Ogi
|
feat(alerts): on demand alert support for apdex and failure rate (#54815)
| false
|
on demand alert support for apdex and failure rate (#54815)
|
feat
|
diff --git a/static/app/views/alerts/rules/metric/utils/onDemandMetricAlert.tsx b/static/app/views/alerts/rules/metric/utils/onDemandMetricAlert.tsx
index b090bd52aa97aa..fa6cc7b859e1c7 100644
--- a/static/app/views/alerts/rules/metric/utils/onDemandMetricAlert.tsx
+++ b/static/app/views/alerts/rules/metric/utils/onDemandMetricAlert.tsx
@@ -11,13 +11,8 @@ export function isValidOnDemandMetricAlert(
return true;
}
- const unsupportedAggregates = [
- AggregationKey.PERCENTILE,
- AggregationKey.APDEX,
- AggregationKey.FAILURE_RATE,
- ];
-
- return !unsupportedAggregates.some(agg => aggregate.includes(agg));
+ // On demand metric alerts do not support generic percentile aggregations
+ return !aggregate.includes(AggregationKey.PERCENTILE);
}
/**
|
ee619dc9065516eb88d0b0f082261582af9f473d
|
2021-01-21 03:44:55
|
Alberto Leal
|
meta: Add dashboards to CODEOWNERS file for the Visibility team (#23120)
| false
|
Add dashboards to CODEOWNERS file for the Visibility team (#23120)
|
meta
|
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index 4629d5cf19f516..b6179fcaee31c6 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -129,6 +129,10 @@ build-utils/ @getsentry/owners-js-build
/tests/js/spec/views/performance/ @getsentry/visibility
/src/sentry/static/sentry/app/utils/discover/ @getsentry/visibility
/tests/js/spec/utils/discover/ @getsentry/visibility
+/src/sentry/static/sentry/app/views/dashboards/ @getsentry/visibility
+/tests/js/spec/views/dashboards/ @getsentry/visibility
+/src/sentry/static/sentry/app/views/dashboardsV2/ @getsentry/visibility
+/tests/js/spec/views/dashboardsV2/ @getsentry/visibility
/src/sentry/static/sentry/app/components/events/interfaces/spans/ @getsentry/visibility
### Endof Perfomance/Discover ###
|
d2578dfe94ca6955d14f2d54e6859daf8079a4a7
|
2023-05-10 00:04:48
|
Ryan Albrecht
|
ref(replays): Refactor breadcrumb accessors to be memoized and central in ReplayReader (#48745)
| false
|
Refactor breadcrumb accessors to be memoized and central in ReplayReader (#48745)
|
ref
|
diff --git a/static/app/components/replays/breadcrumbs/replayTimeline.tsx b/static/app/components/replays/breadcrumbs/replayTimeline.tsx
index 5fe6bf0f269902..c7491f44ff9120 100644
--- a/static/app/components/replays/breadcrumbs/replayTimeline.tsx
+++ b/static/app/components/replays/breadcrumbs/replayTimeline.tsx
@@ -14,17 +14,9 @@ import {TimelineScrubber} from 'sentry/components/replays/player/scrubber';
import useScrubberMouseTracking from 'sentry/components/replays/player/useScrubberMouseTracking';
import {useReplayContext} from 'sentry/components/replays/replayContext';
import {Resizeable} from 'sentry/components/replays/resizeable';
-import {BreadcrumbType} from 'sentry/types/breadcrumbs';
type Props = {};
-const USER_ACTIONS = [
- BreadcrumbType.ERROR,
- BreadcrumbType.NAVIGATION,
- BreadcrumbType.UI,
- BreadcrumbType.USER,
-];
-
function ReplayTimeline({}: Props) {
const {replay} = useReplayContext();
@@ -37,8 +29,7 @@ function ReplayTimeline({}: Props) {
const durationMs = replay.getDurationMs();
const startTimestampMs = replay.getReplay().started_at.getTime();
- const crumbs = replay.getRawCrumbs();
- const userCrumbs = crumbs.filter(crumb => USER_ACTIONS.includes(crumb.type));
+ const userCrumbs = replay.getUserActionCrumbs();
const networkSpans = replay.getNetworkSpans();
return (
diff --git a/static/app/components/replays/replayController.tsx b/static/app/components/replays/replayController.tsx
index 4c224b62fc8e75..9c7d9596d85492 100644
--- a/static/app/components/replays/replayController.tsx
+++ b/static/app/components/replays/replayController.tsx
@@ -23,7 +23,6 @@ import {t} from 'sentry/locale';
import ConfigStore from 'sentry/stores/configStore';
import {useLegacyStore} from 'sentry/stores/useLegacyStore';
import {space} from 'sentry/styles/space';
-import {BreadcrumbType} from 'sentry/types/breadcrumbs';
import {trackAnalytics} from 'sentry/utils/analytics';
import {getNextReplayEvent} from 'sentry/utils/replays/getReplayEvent';
import useFullscreen from 'sentry/utils/replays/hooks/useFullscreen';
@@ -33,14 +32,6 @@ const SECOND = 1000;
const COMPACT_WIDTH_BREAKPOINT = 500;
-const USER_ACTIONS = [
- BreadcrumbType.ERROR,
- BreadcrumbType.INIT,
- BreadcrumbType.NAVIGATION,
- BreadcrumbType.UI,
- BreadcrumbType.USER,
-];
-
interface Props {
speedOptions?: number[];
toggleFullscreen?: () => void;
@@ -92,9 +83,8 @@ function ReplayPlayPauseBar() {
if (!startTimestampMs) {
return;
}
- const transformedCrumbs = replay?.getRawCrumbs() || [];
const next = getNextReplayEvent({
- items: transformedCrumbs.filter(crumb => USER_ACTIONS.includes(crumb.type)),
+ items: replay?.getUserActionCrumbs() || [],
targetTimestampMs: startTimestampMs + currentTime,
});
diff --git a/static/app/components/replays/replayCurrentUrl.tsx b/static/app/components/replays/replayCurrentUrl.tsx
index c8bda924207401..8b38f9ffb93aa3 100644
--- a/static/app/components/replays/replayCurrentUrl.tsx
+++ b/static/app/components/replays/replayCurrentUrl.tsx
@@ -13,7 +13,7 @@ function ReplayCurrentUrl() {
}
const replayRecord = replay.getReplay();
- const crumbs = replay.getRawCrumbs();
+ const crumbs = replay.getNavCrumbs();
return (
<TextCopyInput size="sm">
diff --git a/static/app/components/replays/walker/urlWalker.spec.tsx b/static/app/components/replays/walker/urlWalker.spec.tsx
index f1817251491376..95bbb1178d4b7b 100644
--- a/static/app/components/replays/walker/urlWalker.spec.tsx
+++ b/static/app/components/replays/walker/urlWalker.spec.tsx
@@ -1,7 +1,6 @@
import {render, screen} from 'sentry-test/reactTestingLibrary';
import type {Crumb} from 'sentry/types/breadcrumbs';
-import {BreadcrumbType} from 'sentry/types/breadcrumbs';
import {CrumbWalker, StringWalker} from './urlWalker';
@@ -72,16 +71,5 @@ describe('UrlWalker', () => {
)
).toBeInTheDocument();
});
-
- it('should filter out non-navigation crumbs', () => {
- const ERROR_CRUMB = TestStubs.Breadcrumb({
- type: BreadcrumbType.ERROR,
- });
-
- const crumbs = [ERROR_CRUMB];
-
- render(<CrumbWalker crumbs={crumbs} replayRecord={replayRecord} />);
- expect(screen.getByText('0 Pages')).toBeInTheDocument();
- });
});
});
diff --git a/static/app/components/replays/walker/urlWalker.tsx b/static/app/components/replays/walker/urlWalker.tsx
index abd4cf71f17b89..dc59ce831de53e 100644
--- a/static/app/components/replays/walker/urlWalker.tsx
+++ b/static/app/components/replays/walker/urlWalker.tsx
@@ -19,14 +19,10 @@ export const CrumbWalker = memo(function CrumbWalker({crumbs, replayRecord}: Cru
const startTimestampMs = replayRecord.started_at.getTime();
const {handleClick} = useCrumbHandlers(startTimestampMs);
- const navCrumbs = crumbs.filter(crumb =>
- [BreadcrumbType.INIT, BreadcrumbType.NAVIGATION].includes(crumb.type)
- ) as Crumb[];
-
return (
<ChevronDividedList
items={splitCrumbs({
- crumbs: navCrumbs,
+ crumbs,
startTimestampMs,
onClick: handleClick,
})}
diff --git a/static/app/utils/replays/getCurrentUrl.tsx b/static/app/utils/replays/getCurrentUrl.tsx
index 3c10a1a9df6e6c..6b65b07031ef6a 100644
--- a/static/app/utils/replays/getCurrentUrl.tsx
+++ b/static/app/utils/replays/getCurrentUrl.tsx
@@ -1,7 +1,6 @@
import last from 'lodash/last';
import type {Crumb} from 'sentry/types/breadcrumbs';
-import {BreadcrumbType, BreadcrumbTypeNavigation} from 'sentry/types/breadcrumbs';
import type {ReplayRecord} from 'sentry/views/replays/types';
function parseUrl(url: string) {
@@ -20,16 +19,15 @@ function getCurrentUrl(
const startTimestampMs = replayRecord.started_at.getTime();
const currentTimeMs = startTimestampMs + Math.floor(currentOffsetMS);
- const navigationCrumbs = crumbs.filter(
- crumb => crumb.type === BreadcrumbType.NAVIGATION
- ) as BreadcrumbTypeNavigation[];
-
const initialUrl = replayRecord.urls[0];
const origin = parseUrl(initialUrl)?.origin || initialUrl;
- const mostRecentNavigation = last(
- navigationCrumbs.filter(({timestamp}) => +new Date(timestamp || 0) <= currentTimeMs)
- )?.data?.to;
+ const navigationCrumbs = crumbs.filter(
+ ({timestamp}) => +new Date(timestamp || 0) <= currentTimeMs
+ );
+
+ // @ts-expect-error: Crumb types are not strongly defined in Replay
+ const mostRecentNavigation = last(navigationCrumbs)?.data?.to;
if (!mostRecentNavigation) {
return origin;
diff --git a/static/app/utils/replays/hooks/useExtractedCrumbHtml.tsx b/static/app/utils/replays/hooks/useExtractedCrumbHtml.tsx
index 7e39d411ab2432..546326787f87e1 100644
--- a/static/app/utils/replays/hooks/useExtractedCrumbHtml.tsx
+++ b/static/app/utils/replays/hooks/useExtractedCrumbHtml.tsx
@@ -67,13 +67,7 @@ function useExtractedCrumbHtml({replay}: HookOpts) {
// Get a list of the breadcrumbs that relate directly to the DOM, for each
// crumb we will extract the referenced HTML.
- const crumbs = replay
- .getRawCrumbs()
- .filter(
- crumb =>
- crumb.data && typeof crumb.data === 'object' && 'nodeId' in crumb.data
- );
-
+ const crumbs = replay.getCrumbsWithRRWebNodes();
const rrwebEvents = replay.getRRWebEvents();
// Grab the last event, but skip the synthetic `replay-end` event that the
diff --git a/static/app/utils/replays/replayDataUtils.tsx b/static/app/utils/replays/replayDataUtils.tsx
index a1e63c77b7a919..1eca36d8bb2de1 100644
--- a/static/app/utils/replays/replayDataUtils.tsx
+++ b/static/app/utils/replays/replayDataUtils.tsx
@@ -10,11 +10,7 @@ import type {
Crumb,
RawCrumb,
} from 'sentry/types/breadcrumbs';
-import {
- BreadcrumbLevelType,
- BreadcrumbType,
- isBreadcrumbTypeDefault,
-} from 'sentry/types/breadcrumbs';
+import {BreadcrumbLevelType, BreadcrumbType} from 'sentry/types/breadcrumbs';
import type {
MemorySpanType,
RecordingEvent,
@@ -66,12 +62,6 @@ export const isNetworkSpan = (span: ReplaySpan) => {
return span.op.startsWith('navigation.') || span.op.startsWith('resource.');
};
-export const getBreadcrumbsByCategory = (breadcrumbs: Crumb[], categories: string[]) => {
- return breadcrumbs
- .filter(isBreadcrumbTypeDefault)
- .filter(breadcrumb => categories.includes(breadcrumb.category || ''));
-};
-
export function mapResponseToReplayRecord(apiResponse: any): ReplayRecord {
// Marshal special fields into tags
const user = Object.fromEntries(
diff --git a/static/app/utils/replays/replayReader.tsx b/static/app/utils/replays/replayReader.tsx
index c91d1be3752081..53054698b4deff 100644
--- a/static/app/utils/replays/replayReader.tsx
+++ b/static/app/utils/replays/replayReader.tsx
@@ -1,10 +1,11 @@
import * as Sentry from '@sentry/react';
+import memoize from 'lodash/memoize';
import {duration} from 'moment';
import type {Crumb} from 'sentry/types/breadcrumbs';
+import {BreadcrumbType} from 'sentry/types/breadcrumbs';
import {
breadcrumbFactory,
- getBreadcrumbsByCategory,
isMemorySpan,
isNetworkSpan,
mapRRWebAttachments,
@@ -13,7 +14,6 @@ import {
spansFactory,
} from 'sentry/utils/replays/replayDataUtils';
import type {
- MemorySpanType,
RecordingEvent,
ReplayError,
ReplayRecord,
@@ -84,26 +84,22 @@ export default class ReplayReader {
replayRecord.finished_at.getTime() - replayRecord.started_at.getTime()
);
- const sortedSpans = spansFactory(spans);
- this.networkSpans = sortedSpans.filter(isNetworkSpan);
- this.memorySpans = sortedSpans.filter(isMemorySpan);
-
- this.breadcrumbs = breadcrumbFactory(replayRecord, errors, breadcrumbs, sortedSpans);
- this.consoleCrumbs = getBreadcrumbsByCategory(this.breadcrumbs, ['console', 'issue']);
-
+ this.sortedSpans = spansFactory(spans);
+ this.breadcrumbs = breadcrumbFactory(
+ replayRecord,
+ errors,
+ breadcrumbs,
+ this.sortedSpans
+ );
this.rrwebEvents = rrwebEventListFactory(replayRecord, rrwebEvents);
this.replayRecord = replayRecord;
}
+ private sortedSpans: ReplaySpan[];
private replayRecord: ReplayRecord;
private rrwebEvents: RecordingEvent[];
private breadcrumbs: Crumb[];
- private consoleCrumbs: ReturnType<typeof getBreadcrumbsByCategory>;
- private networkSpans: ReplaySpan[];
- private memorySpans: MemorySpanType[];
-
- private _isDetailsSetup: undefined | boolean;
/**
* @returns Duration of Replay (milliseonds)
@@ -120,30 +116,46 @@ export default class ReplayReader {
return this.rrwebEvents;
};
- getRawCrumbs = () => {
- return this.breadcrumbs;
- };
-
- getConsoleCrumbs = () => {
- return this.consoleCrumbs;
- };
-
- getNetworkSpans = () => {
- return this.networkSpans;
- };
-
- getMemorySpans = () => {
- return this.memorySpans;
- };
-
- isNetworkDetailsSetup = () => {
- if (this._isDetailsSetup === undefined) {
- // TODO(replay): there must be a better way
- const hasHeaders = span =>
+ getCrumbsWithRRWebNodes = memoize(() =>
+ this.breadcrumbs.filter(
+ crumb => crumb.data && typeof crumb.data === 'object' && 'nodeId' in crumb.data
+ )
+ );
+
+ getUserActionCrumbs = memoize(() => {
+ const USER_ACTIONS = [
+ BreadcrumbType.ERROR,
+ BreadcrumbType.INIT,
+ BreadcrumbType.NAVIGATION,
+ BreadcrumbType.UI,
+ BreadcrumbType.USER,
+ ];
+ return this.breadcrumbs.filter(crumb => USER_ACTIONS.includes(crumb.type));
+ });
+
+ getConsoleCrumbs = memoize(() =>
+ this.breadcrumbs.filter(crumb => ['console', 'issue'].includes(crumb.category || ''))
+ );
+
+ getNonConsoleCrumbs = memoize(() =>
+ this.breadcrumbs.filter(crumb => crumb.category !== 'console')
+ );
+
+ getNavCrumbs = memoize(() =>
+ this.breadcrumbs.filter(crumb =>
+ [BreadcrumbType.INIT, BreadcrumbType.NAVIGATION].includes(crumb.type)
+ )
+ );
+
+ getNetworkSpans = memoize(() => this.sortedSpans.filter(isNetworkSpan));
+
+ getMemorySpans = memoize(() => this.sortedSpans.filter(isMemorySpan));
+
+ isNetworkDetailsSetup = memoize(() =>
+ this.getNetworkSpans().some(
+ span =>
Object.keys(span.data.request?.headers || {}).length ||
- Object.keys(span.data.response?.headers || {}).length;
- this._isDetailsSetup = this.networkSpans.some(hasHeaders);
- }
- return this._isDetailsSetup;
- };
+ Object.keys(span.data.response?.headers || {}).length
+ )
+ );
}
diff --git a/static/app/views/replays/detail/breadcrumbs/index.tsx b/static/app/views/replays/detail/breadcrumbs/index.tsx
index 7d72a9003b7e4d..479f2a5a093560 100644
--- a/static/app/views/replays/detail/breadcrumbs/index.tsx
+++ b/static/app/views/replays/detail/breadcrumbs/index.tsx
@@ -34,11 +34,7 @@ const cellMeasurer = {
function Breadcrumbs({breadcrumbs, startTimestampMs}: Props) {
const {currentTime, currentHoverTime} = useReplayContext();
- const items = useMemo(
- () =>
- (breadcrumbs || []).filter(crumb => !['console'].includes(crumb.category || '')),
- [breadcrumbs]
- );
+
const listRef = useRef<ReactVirtualizedList>(null);
// Keep a reference of object paths that are expanded (via <ObjectInspector>)
// by log row, so they they can be restored as the Console pane is scrolling.
@@ -82,7 +78,7 @@ function Breadcrumbs({breadcrumbs, startTimestampMs}: Props) {
[itemLookup, breadcrumbs, currentHoverTime, startTimestampMs]
);
- const deps = useMemo(() => [items], [items]);
+ const deps = useMemo(() => [breadcrumbs], [breadcrumbs]);
const {cache, updateList} = useVirtualizedList({
cellMeasurer,
ref: listRef,
@@ -101,7 +97,7 @@ function Breadcrumbs({breadcrumbs, startTimestampMs}: Props) {
});
const renderRow = ({index, key, style, parent}: ListRowProps) => {
- const item = items[index];
+ const item = (breadcrumbs || [])[index];
return (
<CellMeasurer
@@ -141,7 +137,7 @@ function Breadcrumbs({breadcrumbs, startTimestampMs}: Props) {
)}
overscanRowCount={5}
ref={listRef}
- rowCount={items.length}
+ rowCount={breadcrumbs.length}
rowHeight={cache.rowHeight}
rowRenderer={renderRow}
width={width}
diff --git a/static/app/views/replays/detail/console/consoleFilters.tsx b/static/app/views/replays/detail/console/consoleFilters.tsx
index d1de387c6a852d..0d4eaa4398d296 100644
--- a/static/app/views/replays/detail/console/consoleFilters.tsx
+++ b/static/app/views/replays/detail/console/consoleFilters.tsx
@@ -1,12 +1,12 @@
import {CompactSelect} from 'sentry/components/compactSelect';
import SearchBar from 'sentry/components/searchBar';
import {t} from 'sentry/locale';
-import type {BreadcrumbTypeDefault, Crumb} from 'sentry/types/breadcrumbs';
+import type {Crumb} from 'sentry/types/breadcrumbs';
import useConsoleFilters from 'sentry/views/replays/detail/console/useConsoleFilters';
import FiltersGrid from 'sentry/views/replays/detail/filtersGrid';
type Props = {
- breadcrumbs: undefined | Extract<Crumb, BreadcrumbTypeDefault>[];
+ breadcrumbs: undefined | Crumb[];
} & ReturnType<typeof useConsoleFilters>;
function Filters({
diff --git a/static/app/views/replays/detail/console/index.tsx b/static/app/views/replays/detail/console/index.tsx
index 395da8dd526278..23d391ef4e4f6b 100644
--- a/static/app/views/replays/detail/console/index.tsx
+++ b/static/app/views/replays/detail/console/index.tsx
@@ -9,7 +9,7 @@ import {
import Placeholder from 'sentry/components/placeholder';
import {useReplayContext} from 'sentry/components/replays/replayContext';
import {t} from 'sentry/locale';
-import type {BreadcrumbTypeDefault, Crumb} from 'sentry/types/breadcrumbs';
+import type {Crumb} from 'sentry/types/breadcrumbs';
import ConsoleFilters from 'sentry/views/replays/detail/console/consoleFilters';
import ConsoleLogRow from 'sentry/views/replays/detail/console/consoleLogRow';
import useConsoleFilters from 'sentry/views/replays/detail/console/useConsoleFilters';
@@ -21,7 +21,7 @@ import useVirtualizedList from 'sentry/views/replays/detail/useVirtualizedList';
import useVirtualizedInspector from '../useVirtualizedInspector';
interface Props {
- breadcrumbs: undefined | Extract<Crumb, BreadcrumbTypeDefault>[];
+ breadcrumbs: undefined | Crumb[];
startTimestampMs: number;
}
diff --git a/static/app/views/replays/detail/layout/sidebarArea.tsx b/static/app/views/replays/detail/layout/sidebarArea.tsx
index 27c4acc65bf556..a52f942bbee543 100644
--- a/static/app/views/replays/detail/layout/sidebarArea.tsx
+++ b/static/app/views/replays/detail/layout/sidebarArea.tsx
@@ -14,7 +14,7 @@ function SidebarArea() {
default:
return (
<Breadcrumbs
- breadcrumbs={replay?.getRawCrumbs()}
+ breadcrumbs={replay?.getNonConsoleCrumbs()}
startTimestampMs={replay?.getReplay()?.started_at?.getTime() || 0}
/>
);
diff --git a/static/app/views/replays/details.tsx b/static/app/views/replays/details.tsx
index e367afa7fb2e33..711f2483ed4fde 100644
--- a/static/app/views/replays/details.tsx
+++ b/static/app/views/replays/details.tsx
@@ -172,7 +172,7 @@ function DetailsInsideContext({
return (
<Page
orgSlug={orgSlug}
- crumbs={replay?.getRawCrumbs()}
+ crumbs={replay?.getNavCrumbs()}
replayRecord={replayRecord}
projectSlug={projectSlug}
replayErrors={replayErrors}
|
fd69034862d829904b08d278c0a59d6e0790c05f
|
2018-08-22 01:04:55
|
Lyn Nagara
|
fix(discover): Do not use topK to fetch tags (#9444)
| false
|
Do not use topK to fetch tags (#9444)
|
fix
|
diff --git a/src/sentry/static/sentry/app/views/organizationDiscover/queryBuilder.jsx b/src/sentry/static/sentry/app/views/organizationDiscover/queryBuilder.jsx
index 9d505076f5b43a..09a9db1d45992b 100644
--- a/src/sentry/static/sentry/app/views/organizationDiscover/queryBuilder.jsx
+++ b/src/sentry/static/sentry/app/views/organizationDiscover/queryBuilder.jsx
@@ -63,14 +63,16 @@ export default function createQueryBuilder(initial = {}, organization) {
function load() {
return fetch({
projects: defaultProjects,
- aggregations: [['topK(1000)', 'tags_key', 'tags_key']],
+ fields: ['tags_key'],
+ aggregations: [['count()', null, 'count']],
+ orderby: '-count',
start: moment()
.subtract(90, 'days')
.format(DATE_TIME_FORMAT),
end: moment().format(DATE_TIME_FORMAT),
})
.then(res => {
- tags = res.data[0].tags_key.map(tag => ({name: `tags[${tag}]`, type: 'string'}));
+ tags = res.data.map(tag => ({name: `tags[${tag.tags_key}]`, type: 'string'}));
})
.catch(err => {
tags = PROMOTED_TAGS;
diff --git a/tests/js/spec/views/organizationDiscover/queryBuilder.spec.jsx b/tests/js/spec/views/organizationDiscover/queryBuilder.spec.jsx
index 5ea963c50187ea..c0fb1c607968c3 100644
--- a/tests/js/spec/views/organizationDiscover/queryBuilder.spec.jsx
+++ b/tests/js/spec/views/organizationDiscover/queryBuilder.spec.jsx
@@ -29,7 +29,7 @@ describe('Query Builder', function() {
url: '/organizations/org-slug/discover/',
method: 'POST',
body: {
- data: [{tags_key: ['tag1', 'tag2']}],
+ data: [{tags_key: 'tag1', count: 5}, {tags_key: 'tag2', count: 1}],
},
});
const queryBuilder = createQueryBuilder(
@@ -42,7 +42,9 @@ describe('Query Builder', function() {
'/organizations/org-slug/discover/',
expect.objectContaining({
data: expect.objectContaining({
- aggregations: [['topK(1000)', 'tags_key', 'tags_key']],
+ fields: ['tags_key'],
+ aggregations: [['count()', null, 'count']],
+ orderby: '-count',
projects: [2],
start: '2017-07-19T02:41:20',
end: '2017-10-17T02:41:20',
|
88cc5be7bd5ef74dff9ff30992ea83105b46e29a
|
2023-11-02 19:21:16
|
Leander Rodrigues
|
tests(hybrid-cloud): Stabilize access log middleware tests (#59193)
| false
|
Stabilize access log middleware tests (#59193)
|
tests
|
diff --git a/src/sentry/api/bases/organization.py b/src/sentry/api/bases/organization.py
index d3d847001bf9e1..2ba60739f877be 100644
--- a/src/sentry/api/bases/organization.py
+++ b/src/sentry/api/bases/organization.py
@@ -236,6 +236,10 @@ def convert_args(
kwargs["organization_context"] = organization_context
kwargs["organization"] = organization_context.organization
+
+ # Used for API access logs
+ request._request.organization = organization_context.organization # type: ignore
+
return (args, kwargs)
diff --git a/tests/sentry/middleware/test_access_log_middleware.py b/tests/sentry/middleware/test_access_log_middleware.py
index 87b6c9d9fc0a91..b6c6a84b2f0fdf 100644
--- a/tests/sentry/middleware/test_access_log_middleware.py
+++ b/tests/sentry/middleware/test_access_log_middleware.py
@@ -1,18 +1,25 @@
import logging
+from urllib.parse import unquote
import pytest
from django.test import override_settings
-from django.urls import re_path
+from django.urls import re_path, reverse
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from sentry.api.base import Endpoint
-from sentry.api.bases.organization import OrganizationEndpoint
+from sentry.api.bases.organization import ControlSiloOrganizationEndpoint, OrganizationEndpoint
+from sentry.api.endpoints.rpc import RpcServiceEndpoint
from sentry.models.apitoken import ApiToken
-from sentry.models.outbox import outbox_context
from sentry.ratelimits.config import RateLimitConfig
+from sentry.silo.base import SiloMode
from sentry.testutils.cases import APITestCase
-from sentry.testutils.silo import control_silo_test, region_silo_test
+from sentry.testutils.silo import (
+ all_silo_test,
+ assume_test_silo_mode,
+ control_silo_test,
+ region_silo_test,
+)
from sentry.types.ratelimit import RateLimit, RateLimitCategory
@@ -66,6 +73,43 @@ def get(self, request):
return Response({"ok": True})
+class MyOrganizationEndpoint(OrganizationEndpoint):
+ def get(self, request, organization):
+ return Response({"ok": True})
+
+
+class MyControlOrganizationEndpoint(ControlSiloOrganizationEndpoint):
+ def get(self, request, organization_context, organization):
+ return Response({"ok": True})
+
+
+urlpatterns = [
+ re_path(r"^/dummy$", DummyEndpoint.as_view(), name="dummy-endpoint"),
+ re_path(r"^/dummyfail$", DummyFailEndpoint.as_view(), name="dummy-fail-endpoint"),
+ re_path(r"^/dummyratelimit$", RateLimitedEndpoint.as_view(), name="ratelimit-endpoint"),
+ re_path(
+ r"^/dummyratelimitconcurrent$",
+ ConcurrentRateLimitedEndpoint.as_view(),
+ name="concurrent-ratelimit-endpoint",
+ ),
+ re_path(
+ r"^(?P<organization_slug>[^\/]+)/stats_v2/$",
+ MyOrganizationEndpoint.as_view(),
+ name="sentry-api-0-organization-stats-v2",
+ ),
+ re_path(
+ r"^(?P<organization_slug>[^\/]+)/members/$",
+ MyControlOrganizationEndpoint.as_view(),
+ name="sentry-api-0-organization-members",
+ ),
+ # Need to retain RPC endpoint for cross-silo calls
+ re_path(
+ r"^rpc/(?P<service_name>\w+)/(?P<method_name>\w+)/$",
+ RpcServiceEndpoint.as_view(),
+ name="sentry-api-0-rpc-service",
+ ),
+]
+
access_log_fields = (
"method",
"view",
@@ -91,28 +135,6 @@ def get(self, request):
)
-class MyOrganizationEndpoint(OrganizationEndpoint):
- def get(self, request, organization):
- return Response({"ok": True})
-
-
-urlpatterns = [
- re_path(r"^/dummy$", DummyEndpoint.as_view(), name="dummy-endpoint"),
- re_path(r"^/dummyfail$", DummyFailEndpoint.as_view(), name="dummy-fail-endpoint"),
- re_path(r"^/dummyratelimit$", RateLimitedEndpoint.as_view(), name="ratelimit-endpoint"),
- re_path(
- r"^/dummyratelimitconcurrent$",
- ConcurrentRateLimitedEndpoint.as_view(),
- name="concurrent-ratelimit-endpoint",
- ),
- re_path(
- r"^(?P<organization_slug>[^\/]+)/stats_v2/$",
- MyOrganizationEndpoint.as_view(),
- name="sentry-api-0-organization-stats-v2",
- ),
-]
-
-
@override_settings(ROOT_URLCONF="tests.sentry.middleware.test_access_log_middleware")
@override_settings(LOG_API_ACCESS=True)
class LogCaptureAPITestCase(APITestCase):
@@ -130,7 +152,12 @@ def assert_access_log_recorded(self):
def captured_logs(self):
return [r for r in self._caplog.records if r.name == "sentry.access.api"]
+ def get_tested_log(self, **kwargs):
+ tested_log_path = unquote(reverse(self.endpoint, **kwargs))
+ return next(log for log in self.captured_logs if log.path == tested_log_path)
+
+@all_silo_test(stable=True)
@override_settings(SENTRY_SELF_HOSTED=False)
class TestAccessLogRateLimited(LogCaptureAPITestCase):
@@ -147,6 +174,7 @@ def test_access_log_rate_limited(self):
assert self.captured_logs[0].group == RateLimitedEndpoint.rate_limits.group
+@all_silo_test(stable=True)
@override_settings(SENTRY_SELF_HOSTED=False)
class TestAccessLogConcurrentRateLimited(LogCaptureAPITestCase):
@@ -172,34 +200,38 @@ def test_concurrent_request_finishes(self):
assert int(self.captured_logs[i].remaining) < 20
-@control_silo_test
+@all_silo_test(stable=True)
class TestAccessLogSuccess(LogCaptureAPITestCase):
endpoint = "dummy-endpoint"
def test_access_log_success(self):
self._caplog.set_level(logging.INFO, logger="sentry")
- token = ApiToken.objects.create(user=self.user, scope_list=["event:read", "org:read"])
+ token = None
+ with assume_test_silo_mode(SiloMode.CONTROL):
+ token = ApiToken.objects.create(user=self.user, scope_list=["event:read", "org:read"])
self.login_as(user=self.create_user())
self.get_success_response(extra_headers={"HTTP_AUTHORIZATION": f"Bearer {token.token}"})
self.assert_access_log_recorded()
- assert self.captured_logs[0].token_type == "api_token"
+ assert self.get_tested_log().token_type == "api_token"
+@all_silo_test(stable=True)
@override_settings(LOG_API_ACCESS=False)
-@control_silo_test(stable=True)
class TestAccessLogSuccessNotLoggedInDev(LogCaptureAPITestCase):
endpoint = "dummy-endpoint"
def test_access_log_success(self):
- with outbox_context(flush=False):
+ token = None
+ with assume_test_silo_mode(SiloMode.CONTROL):
token = ApiToken.objects.create(user=self.user, scope_list=["event:read", "org:read"])
self.login_as(user=self.create_user())
self.get_success_response(extra_headers={"HTTP_AUTHORIZATION": f"Bearer {token.token}"})
assert len(self.captured_logs) == 0
+@all_silo_test(stable=True)
class TestAccessLogFail(LogCaptureAPITestCase):
endpoint = "dummy-fail-endpoint"
@@ -208,8 +240,8 @@ def test_access_log_fail(self):
self.assert_access_log_recorded()
-@region_silo_test
-class TestOrganizationIdPresent(LogCaptureAPITestCase):
+@region_silo_test(stable=True)
+class TestOrganizationIdPresentForRegion(LogCaptureAPITestCase):
endpoint = "sentry-api-0-organization-stats-v2"
def setUp(self):
@@ -228,4 +260,29 @@ def test_org_id_populated(self):
},
)
- assert self.captured_logs[0].organization_id == str(self.organization.id)
+ tested_log = self.get_tested_log(args=[self.organization.slug])
+ assert tested_log.organization_id == str(self.organization.id)
+
+
+@control_silo_test(stable=True)
+class TestOrganizationIdPresentForControl(LogCaptureAPITestCase):
+ endpoint = "sentry-api-0-organization-members"
+
+ def setUp(self):
+ self.login_as(user=self.user)
+
+ def test_org_id_populated(self):
+ self._caplog.set_level(logging.INFO, logger="sentry")
+ self.get_success_response(
+ self.organization.slug,
+ qs_params={
+ "project": [-1],
+ "category": ["error"],
+ "statsPeriod": "1d",
+ "interval": "1d",
+ "field": ["sum(quantity)"],
+ },
+ )
+
+ tested_log = self.get_tested_log(args=[self.organization.slug])
+ assert tested_log.organization_id == str(self.organization.id)
|
ba42214e5507ec4793e2711619a23d40194baa0e
|
2022-04-27 02:25:43
|
Richard Ma
|
chore(superuser): Added metrics for success rate of superuser class (#33944)
| false
|
Added metrics for success rate of superuser class (#33944)
|
chore
|
diff --git a/src/sentry/auth/superuser.py b/src/sentry/auth/superuser.py
index 55e3cd08ba3f28..cf7d7067d6ceb5 100644
--- a/src/sentry/auth/superuser.py
+++ b/src/sentry/auth/superuser.py
@@ -22,7 +22,7 @@
from sentry.api.exceptions import SentryAPIException
from sentry.auth.system import is_system_auth
-from sentry.utils import json
+from sentry.utils import json, metrics
from sentry.utils.auth import has_completed_sso
from sentry.utils.settings import is_self_hosted
@@ -336,6 +336,11 @@ def enable_and_log_superuser_access():
current_datetime=current_datetime,
)
+ metrics.incr(
+ "superuser.success",
+ sample_rate=1.0,
+ )
+
logger.info(
"superuser.logged-in",
extra={"ip_address": request.META["REMOTE_ADDR"], "user_id": user.id},
@@ -349,8 +354,18 @@ def enable_and_log_superuser_access():
# need to use json loads as the data is no longer in request.data
su_access_json = json.loads(request.body)
except json.JSONDecodeError:
+ metrics.incr(
+ "superuser.failure",
+ sample_rate=1.0,
+ tags={"reason": SuperuserAccessFormInvalidJson.code},
+ )
raise SuperuserAccessFormInvalidJson()
except AttributeError:
+ metrics.incr(
+ "superuser.failure",
+ sample_rate=1.0,
+ tags={"reason": EmptySuperuserAccessForm.code},
+ )
raise EmptySuperuserAccessForm()
su_access_info = SuperuserAccessSerializer(data=su_access_json)
@@ -371,6 +386,7 @@ def enable_and_log_superuser_access():
)
enable_and_log_superuser_access()
except AttributeError:
+ metrics.incr("superuser.failure", sample_rate=1.0, tags={"reason": "missing-user-info"})
logger.error("superuser.superuser_access.missing_user_info")
def set_logged_out(self):
|
ee314350062d346c31f6acafb743bbd60ee276c7
|
2020-07-23 21:54:28
|
Billy Vong
|
test(jest): Fix flakey `<OrganizationContext>` (maybe) and `<IssueList>` (#20003)
| false
|
Fix flakey `<OrganizationContext>` (maybe) and `<IssueList>` (#20003)
|
test
|
diff --git a/tests/js/spec/views/issueList/overview.spec.jsx b/tests/js/spec/views/issueList/overview.spec.jsx
index 8a0e845c5fdbba..508255a69f20a0 100644
--- a/tests/js/spec/views/issueList/overview.spec.jsx
+++ b/tests/js/spec/views/issueList/overview.spec.jsx
@@ -264,6 +264,7 @@ describe('IssueList', function() {
// Update stores with saved searches
await tick();
+ await tick();
wrapper.update();
// Main /issues/ request
@@ -298,6 +299,7 @@ describe('IssueList', function() {
});
createWrapper();
+ await tick();
await tick();
wrapper.update();
@@ -332,6 +334,7 @@ describe('IssueList', function() {
});
createWrapper();
+ await tick();
await tick();
wrapper.update();
@@ -366,6 +369,7 @@ describe('IssueList', function() {
});
createWrapper({params: {searchId: '123'}});
+ await tick();
await tick();
wrapper.update();
@@ -400,6 +404,7 @@ describe('IssueList', function() {
});
createWrapper({location: {query: {query: 'level:error'}}});
+ await tick();
await tick();
wrapper.update();
@@ -433,6 +438,7 @@ describe('IssueList', function() {
});
createWrapper({location: {query: {query: ''}}});
+ await tick();
await tick();
wrapper.update();
@@ -458,6 +464,7 @@ describe('IssueList', function() {
});
createWrapper();
await tick();
+ await tick();
wrapper.update();
wrapper.find('SavedSearchSelector DropdownButton').simulate('click');
@@ -521,6 +528,7 @@ describe('IssueList', function() {
});
createWrapper();
await tick();
+ await tick();
await wrapper.update();
// Update the search input
@@ -551,6 +559,7 @@ describe('IssueList', function() {
});
createWrapper();
await tick();
+ await tick();
wrapper.update();
const createPin = MockApiClient.addMockResponse({
@@ -660,6 +669,7 @@ describe('IssueList', function() {
});
createWrapper();
await tick();
+ await tick();
wrapper.update();
let createPin = MockApiClient.addMockResponse({
@@ -808,6 +818,7 @@ describe('IssueList', function() {
location: {query: {project: ['123'], environment: ['prod']}},
});
await tick();
+ await tick();
wrapper.update();
const deletePin = MockApiClient.addMockResponse({
diff --git a/tests/js/spec/views/organizationContext.spec.jsx b/tests/js/spec/views/organizationContext.spec.jsx
index 9293b03a4b7578..77ffd37d72b69c 100644
--- a/tests/js/spec/views/organizationContext.spec.jsx
+++ b/tests/js/spec/views/organizationContext.spec.jsx
@@ -53,10 +53,16 @@ describe('OrganizationContext', function() {
});
afterEach(async function() {
+ // Ugh these stores are a pain
+ // It's possible that a test still has an update action in flight
+ // and caues store to update *AFTER* we reset. Attempt to flush out updates
+ await tick();
+ await tick();
wrapper.unmount();
OrganizationStore.reset();
// await for store change to finish propagating
await tick();
+ await tick();
TeamStore.loadInitialData.mockRestore();
ProjectsStore.loadInitialData.mockRestore();
|
5f3b3d850adfa8136e0ce647d7920542d3fdd600
|
2021-11-16 06:19:46
|
Evan Purkhiser
|
feat(js): Support slug loading + searching in useProjects (#29893)
| false
|
Support slug loading + searching in useProjects (#29893)
|
feat
|
diff --git a/static/app/utils/useProjects.tsx b/static/app/utils/useProjects.tsx
index 0b43005a458a48..304593fd38060e 100644
--- a/static/app/utils/useProjects.tsx
+++ b/static/app/utils/useProjects.tsx
@@ -1,13 +1,315 @@
+import {useEffect, useRef, useState} from 'react';
+import uniqBy from 'lodash/uniqBy';
+
+import ProjectActions from 'app/actions/projectActions';
+import {Client} from 'app/api';
+import OrganizationStore from 'app/stores/organizationStore';
import ProjectsStore from 'app/stores/projectsStore';
import {useLegacyStore} from 'app/stores/useLegacyStore';
+import {AvatarProject, Project} from 'app/types';
+import parseLinkHeader from 'app/utils/parseLinkHeader';
+import RequestError from 'app/utils/requestError/requestError';
+import useApi from 'app/utils/useApi';
+
+type ProjectPlaceholder = AvatarProject;
+
+type State = {
+ /**
+ * Reflects whether or not the initial fetch for the requested projects
+ * was fulfilled. This accounts for both the store and specifically loaded
+ * slugs.
+ */
+ initiallyLoaded: boolean;
+ /**
+ * This is state for when fetching data from API
+ */
+ fetching: boolean;
+ /**
+ * The error that occurred if fetching failed
+ */
+ fetchError: null | RequestError;
+ /**
+ * Indicates that Project results (from API) are paginated and there are more
+ * projects that are not in the initial response
+ */
+ hasMore: null | boolean;
+ /**
+ * The last query we searched. Used to validate the cursor
+ */
+ lastSearch: null | string;
+ /**
+ * Pagination
+ */
+ nextCursor?: null | string;
+};
+
+type Result = {
+ /**
+ * The loaded projects list
+ */
+ projects: Project[];
+ /**
+ * When loading specific slugs, placeholder objects will be returned
+ */
+ placeholders: ProjectPlaceholder[];
+ /**
+ * This is an action provided to consumers for them to update the current
+ * projects result set using a simple search query.
+ *
+ * Will always add new options into the store.
+ */
+ onSearch: (searchTerm: string) => Promise<void>;
+} & Pick<State, 'fetching' | 'hasMore' | 'fetchError' | 'initiallyLoaded'>;
+
+type Options = {
+ /**
+ * Specify an orgId, overriding the organization in the current context
+ */
+ orgId?: string;
+ /**
+ * List of slugs to look for summaries for, this can be from `props.projects`,
+ * otherwise fetch from API
+ */
+ slugs?: string[];
+ /**
+ * Number of projects to return when not using `props.slugs`
+ */
+ limit?: number;
+};
+
+type FetchProjectsOptions = {
+ slugs?: string[];
+ limit?: Options['limit'];
+ cursor?: State['nextCursor'];
+ search?: State['lastSearch'];
+ lastSearch?: State['lastSearch'];
+};
+
+/**
+ * Helper function to actually load projects
+ */
+async function fetchProjects(
+ api: Client,
+ orgId: string,
+ {slugs, search, limit, lastSearch, cursor}: FetchProjectsOptions = {}
+) {
+ const query: {
+ collapse: string[];
+ query?: string;
+ cursor?: typeof cursor;
+ per_page?: number;
+ all_projects?: number;
+ } = {
+ // Never return latestDeploys project property from api
+ collapse: ['latestDeploys'],
+ };
+
+ if (slugs !== undefined && slugs.length > 0) {
+ query.query = slugs.map(slug => `slug:${slug}`).join(' ');
+ }
+
+ if (search) {
+ query.query = `${query.query ?? ''}${search}`.trim();
+ }
+
+ const prevSearchMatches = (!lastSearch && !search) || lastSearch === search;
+
+ if (prevSearchMatches && cursor) {
+ query.cursor = cursor;
+ }
+
+ if (limit !== undefined) {
+ query.per_page = limit;
+ }
+
+ let hasMore: null | boolean = false;
+ let nextCursor: null | string = null;
+ const [data, , resp] = await api.requestPromise(`/organizations/${orgId}/projects/`, {
+ includeAllArgs: true,
+ query,
+ });
+
+ const pageLinks = resp?.getResponseHeader('Link');
+ if (pageLinks) {
+ const paginationObject = parseLinkHeader(pageLinks);
+ hasMore = paginationObject?.next?.results || paginationObject?.previous?.results;
+ nextCursor = paginationObject?.next?.cursor;
+ }
+
+ return {results: data, hasMore, nextCursor};
+}
/**
* Provides projects from the ProjectStore
+ *
+ * This hook also provides a way to select specific project slugs, and search
+ * (type-ahead) for more projects that may not be in the project store.
+ *
+ * NOTE: Currently ALL projects are always loaded, but this hook is designed
+ * for future-compat in a world where we do _not_ load all projects.
*/
-function useProjects() {
- const {projects, loading} = useLegacyStore(ProjectsStore);
+function useProjects({limit, slugs, orgId: propOrgId}: Options = {}) {
+ const api = useApi();
+
+ const {organization} = useLegacyStore(OrganizationStore);
+ const store = useLegacyStore(ProjectsStore);
+
+ const orgId = propOrgId ?? organization?.slug;
+
+ const storeSlugs = new Set(store.projects.map(t => t.slug));
+ const slugsToLoad = slugs?.filter(slug => !storeSlugs.has(slug)) ?? [];
+ const shouldLoadSlugs = slugsToLoad.length > 0;
+
+ const [state, setState] = useState<State>({
+ initiallyLoaded: !store.loading && !shouldLoadSlugs,
+ fetching: shouldLoadSlugs,
+ hasMore: null,
+ lastSearch: null,
+ nextCursor: null,
+ fetchError: null,
+ });
+
+ const slugsRef = useRef<Set<string> | null>(null);
+
+ // Only initialize slugsRef.current once and modify it when we receive new
+ // slugs determined through set equality
+ if (slugs !== undefined) {
+ if (slugsRef.current === null) {
+ slugsRef.current = new Set(slugs);
+ }
+
+ if (
+ slugs.length !== slugsRef.current.size ||
+ slugs.some(slug => !slugsRef.current?.has(slug))
+ ) {
+ slugsRef.current = new Set(slugs);
+ }
+ }
+
+ async function loadProjectsBySlug() {
+ if (orgId === undefined) {
+ // eslint-disable-next-line no-console
+ console.error('Cannot use useProjects({slugs}) without an organization in context');
+ return;
+ }
+
+ setState({...state, fetching: true});
+ try {
+ const {results, hasMore, nextCursor} = await fetchProjects(api, orgId, {
+ slugs: slugsToLoad,
+ limit,
+ });
+
+ const fetchedProjects = uniqBy([...store.projects, ...results], ({slug}) => slug);
+ ProjectActions.loadProjects(fetchedProjects);
+
+ setState({
+ ...state,
+ hasMore,
+ fetching: false,
+ initiallyLoaded: !store.loading,
+ nextCursor,
+ });
+ } catch (err) {
+ console.error(err); // eslint-disable-line no-console
+
+ setState({
+ ...state,
+ fetching: false,
+ initiallyLoaded: !store.loading,
+ fetchError: err,
+ });
+ }
+ }
+
+ async function handleSearch(search: string) {
+ const {lastSearch} = state;
+ const cursor = state.nextCursor;
+
+ if (search === '') {
+ return;
+ }
+
+ if (orgId === undefined) {
+ // eslint-disable-next-line no-console
+ console.error('Cannot use useProjects.onSearch without an organization in context');
+ return;
+ }
+
+ setState({...state, fetching: true});
+
+ try {
+ api.clear();
+ const {results, hasMore, nextCursor} = await fetchProjects(api, orgId, {
+ search,
+ limit,
+ lastSearch,
+ cursor,
+ });
+
+ const fetchedProjects = uniqBy([...store.projects, ...results], ({slug}) => slug);
+
+ // Only update the store if we have more items
+ if (fetchedProjects.length > store.projects.length) {
+ ProjectActions.loadProjects(fetchedProjects);
+ }
+
+ setState({
+ ...state,
+ hasMore,
+ fetching: false,
+ lastSearch: search,
+ nextCursor,
+ });
+ } catch (err) {
+ console.error(err); // eslint-disable-line no-console
+
+ setState({...state, fetching: false, fetchError: err});
+ }
+ }
+
+ useEffect(() => {
+ // Load specified team slugs
+ if (shouldLoadSlugs) {
+ loadProjectsBySlug();
+ return;
+ }
+ }, [slugsRef.current]);
+
+ // Update initiallyLoaded when we finish loading within the projectStore
+ useEffect(() => {
+ const storeLoaded = !store.loading;
+
+ if (state.initiallyLoaded === storeLoaded) {
+ return;
+ }
+
+ if (shouldLoadSlugs) {
+ return;
+ }
+
+ setState({...state, initiallyLoaded: storeLoaded});
+ }, [store.loading]);
+
+ const {initiallyLoaded, fetching, fetchError, hasMore} = state;
+
+ const filteredProjects = slugs
+ ? store.projects.filter(t => slugs.includes(t.slug))
+ : store.projects;
+
+ const placeholders = slugsToLoad.map(slug => ({slug}));
+
+ const result: Result = {
+ projects: filteredProjects,
+ placeholders,
+ fetching: fetching || store.loading,
+ initiallyLoaded,
+ fetchError,
+ hasMore,
+ onSearch: handleSearch,
+ };
- return {projects, loadingProjects: loading};
+ return result;
}
export default useProjects;
diff --git a/static/app/utils/withProjects.tsx b/static/app/utils/withProjects.tsx
index 8bb656c860f6cd..7970b3cf2b1e9a 100644
--- a/static/app/utils/withProjects.tsx
+++ b/static/app/utils/withProjects.tsx
@@ -18,7 +18,8 @@ function withProjects<P extends InjectedProjectsProps>(
type Props = Omit<P, keyof InjectedProjectsProps>;
const Wrapper: React.FC<Props> = props => {
- const {projects, loadingProjects} = useProjects();
+ const {projects, initiallyLoaded} = useProjects();
+ const loadingProjects = !initiallyLoaded;
return <WrappedComponent {...(props as P)} {...{projects, loadingProjects}} />;
};
diff --git a/tests/js/spec/components/contextPickerModal.spec.jsx b/tests/js/spec/components/contextPickerModal.spec.jsx
index 85288375f0e2f6..9776e4d465883a 100644
--- a/tests/js/spec/components/contextPickerModal.spec.jsx
+++ b/tests/js/spec/components/contextPickerModal.spec.jsx
@@ -28,8 +28,8 @@ describe('ContextPickerModal', function () {
});
afterEach(async function () {
- OrganizationsStore.load([]);
- OrganizationStore.reset();
+ act(() => OrganizationsStore.load([]));
+ act(() => OrganizationStore.reset());
await act(tick);
});
diff --git a/tests/js/spec/components/organizations/globalSelectionHeader.spec.jsx b/tests/js/spec/components/organizations/globalSelectionHeader.spec.jsx
index 19af4dd0bae27b..8a5b724314e91e 100644
--- a/tests/js/spec/components/organizations/globalSelectionHeader.spec.jsx
+++ b/tests/js/spec/components/organizations/globalSelectionHeader.spec.jsx
@@ -1,4 +1,4 @@
-import {mountWithTheme} from 'sentry-test/enzyme';
+import {enforceActOnUseLegacyStoreHook, mountWithTheme} from 'sentry-test/enzyme';
import {initializeOrg} from 'sentry-test/initializeOrg';
import {mockRouterPush} from 'sentry-test/mockRouterPush';
import {act} from 'sentry-test/reactTestingLibrary';
@@ -30,6 +30,8 @@ jest.mock('app/utils/localStorage', () => ({
}));
describe('GlobalSelectionHeader', function () {
+ enforceActOnUseLegacyStoreHook();
+
let wrapper;
const {organization, router, routerContext} = initializeOrg({
organization: {features: ['global-views']},
@@ -60,7 +62,7 @@ describe('GlobalSelectionHeader', function () {
beforeEach(function () {
MockApiClient.clearMockResponses();
- act(() => ProjectsStore.loadInitialData(organization.projects));
+ ProjectsStore.loadInitialData(organization.projects);
getItem.mockImplementation(() => null);
MockApiClient.addMockResponse({
@@ -229,7 +231,7 @@ describe('GlobalSelectionHeader', function () {
params: {orgId: 'org-slug'},
},
});
- act(() => ProjectsStore.loadInitialData(initialData.projects));
+ ProjectsStore.loadInitialData(initialData.projects);
wrapper = mountWithTheme(
<GlobalSelectionHeader
@@ -532,7 +534,7 @@ describe('GlobalSelectionHeader', function () {
body: [],
});
- act(() => ProjectsStore.reset());
+ ProjectsStore.reset();
// This can happen when you switch organization so params.orgId !== the
// current org in context In this case params.orgId = 'org-slug'
@@ -602,7 +604,7 @@ describe('GlobalSelectionHeader', function () {
const project = TestStubs.Project({id: '3'});
const org = TestStubs.Organization({projects: [project]});
- act(() => ProjectsStore.loadInitialData(org.projects));
+ ProjectsStore.loadInitialData(org.projects);
const initializationObj = initializeOrg({
organization: org,
@@ -642,7 +644,7 @@ describe('GlobalSelectionHeader', function () {
},
});
- act(() => ProjectsStore.loadInitialData(initialData.projects));
+ ProjectsStore.loadInitialData(initialData.projects);
wrapper = mountWithTheme(
<GlobalSelectionHeader
@@ -697,7 +699,7 @@ describe('GlobalSelectionHeader', function () {
};
beforeEach(function () {
- act(() => ProjectsStore.loadInitialData(initialData.projects));
+ ProjectsStore.loadInitialData(initialData.projects);
initialData.router.push.mockClear();
initialData.router.replace.mockClear();
@@ -715,7 +717,7 @@ describe('GlobalSelectionHeader', function () {
});
it('appends projectId to URL when `forceProject` becomes available (async)', async function () {
- act(() => ProjectsStore.reset());
+ ProjectsStore.reset();
// forceProject generally starts undefined
createWrapper({shouldForceProject: true});
@@ -789,7 +791,7 @@ describe('GlobalSelectionHeader', function () {
params: {orgId: 'org-slug'},
},
});
- act(() => ProjectsStore.loadInitialData(initialData.projects));
+ ProjectsStore.loadInitialData(initialData.projects);
const createWrapper = props => {
wrapper = mountWithTheme(
@@ -856,7 +858,7 @@ describe('GlobalSelectionHeader', function () {
};
beforeEach(function () {
- act(() => ProjectsStore.loadInitialData(initialData.projects));
+ ProjectsStore.loadInitialData(initialData.projects);
initialData.router.push.mockClear();
initialData.router.replace.mockClear();
@@ -872,7 +874,7 @@ describe('GlobalSelectionHeader', function () {
});
it('does not append projectId to URL when `loadingProjects` changes and finishes loading', async function () {
- act(() => ProjectsStore.reset());
+ ProjectsStore.reset();
createWrapper();
@@ -887,7 +889,7 @@ describe('GlobalSelectionHeader', function () {
});
it('appends projectId to URL when `forceProject` becomes available (async)', async function () {
- act(() => ProjectsStore.reset());
+ ProjectsStore.reset();
// forceProject generally starts undefined
createWrapper({shouldForceProject: true});
@@ -942,7 +944,7 @@ describe('GlobalSelectionHeader', function () {
},
});
- act(() => ProjectsStore.loadInitialData(initialData.projects));
+ ProjectsStore.loadInitialData(initialData.projects);
wrapper = mountWithTheme(
<GlobalSelectionHeader organization={initialData.organization} />,
@@ -1093,7 +1095,7 @@ describe('GlobalSelectionHeader', function () {
});
beforeEach(function () {
- act(() => ProjectsStore.loadInitialData(initialData.projects));
+ ProjectsStore.loadInitialData(initialData.projects);
});
it('shows IconProject when no projects are selected', async function () {
diff --git a/tests/js/spec/utils/useProjects.spec.tsx b/tests/js/spec/utils/useProjects.spec.tsx
new file mode 100644
index 00000000000000..61c4145b248107
--- /dev/null
+++ b/tests/js/spec/utils/useProjects.spec.tsx
@@ -0,0 +1,94 @@
+import {act, renderHook} from '@testing-library/react-hooks';
+
+import OrganizationStore from 'app/stores/organizationStore';
+import ProjectsStore from 'app/stores/projectsStore';
+import useProjects from 'app/utils/useProjects';
+
+describe('useProjects', function () {
+ const org = TestStubs.Organization();
+
+ const mockProjects = [TestStubs.Project()];
+
+ it('provides projects from the team store', function () {
+ act(() => void ProjectsStore.loadInitialData(mockProjects));
+
+ const {result} = renderHook(() => useProjects());
+ const {projects} = result.current;
+
+ expect(projects).toEqual(mockProjects);
+ });
+
+ it('loads more projects when using onSearch', async function () {
+ act(() => void ProjectsStore.loadInitialData(mockProjects));
+ act(() => void OrganizationStore.onUpdate(org, {replace: true}));
+
+ const newProject3 = TestStubs.Project({id: '3', slug: 'test-project3'});
+ const newProject4 = TestStubs.Project({id: '4', slug: 'test-project4'});
+
+ const mockRequest = MockApiClient.addMockResponse({
+ url: `/organizations/${org.slug}/projects/`,
+ method: 'GET',
+ body: [newProject3, newProject4],
+ });
+
+ const {result, waitFor} = renderHook(() => useProjects());
+ const {onSearch} = result.current;
+
+ // Works with append
+ const onSearchPromise = act(() => onSearch('test'));
+
+ expect(result.current.fetching).toBe(true);
+ await onSearchPromise;
+ expect(result.current.fetching).toBe(false);
+
+ // Wait for state to be reflected from the store
+ await waitFor(() => result.current.projects.length === 3);
+
+ expect(mockRequest).toHaveBeenCalled();
+ expect(result.current.projects).toEqual([...mockProjects, newProject3, newProject4]);
+
+ // de-duplicates itesm in the query results
+ mockRequest.mockClear();
+ await act(() => onSearch('test'));
+
+ // No new items have been added
+ expect(mockRequest).toHaveBeenCalled();
+ expect(result.current.projects).toEqual([...mockProjects, newProject3, newProject4]);
+ });
+
+ it('provides only the specified slugs', async function () {
+ act(() => void ProjectsStore.loadInitialData(mockProjects));
+ act(() => void OrganizationStore.onUpdate(org, {replace: true}));
+
+ const projectFoo = TestStubs.Project({id: 3, slug: 'foo'});
+ const mockRequest = MockApiClient.addMockResponse({
+ url: `/organizations/${org.slug}/projects/`,
+ method: 'GET',
+ body: [projectFoo],
+ });
+
+ const {result, waitFor} = renderHook(props => useProjects(props), {
+ initialProps: {slugs: ['foo']},
+ });
+
+ expect(result.current.initiallyLoaded).toBe(false);
+ expect(mockRequest).toHaveBeenCalled();
+
+ await waitFor(() => expect(result.current.projects.length).toBe(1));
+
+ const {projects} = result.current;
+ expect(projects).toEqual(expect.arrayContaining([projectFoo]));
+ });
+
+ it('only loads slugs when needed', async function () {
+ act(() => void ProjectsStore.loadInitialData(mockProjects));
+
+ const {result} = renderHook(props => useProjects(props), {
+ initialProps: {slugs: [mockProjects[0].slug]},
+ });
+
+ const {projects, initiallyLoaded} = result.current;
+ expect(initiallyLoaded).toBe(true);
+ expect(projects).toEqual(expect.arrayContaining(mockProjects));
+ });
+});
diff --git a/tests/js/spec/views/settings/organizationGeneralSettings/index.spec.jsx b/tests/js/spec/views/settings/organizationGeneralSettings/index.spec.jsx
index 15237f78bee054..5a48dca9b34462 100644
--- a/tests/js/spec/views/settings/organizationGeneralSettings/index.spec.jsx
+++ b/tests/js/spec/views/settings/organizationGeneralSettings/index.spec.jsx
@@ -1,6 +1,6 @@
import {browserHistory} from 'react-router';
-import {mountWithTheme} from 'sentry-test/enzyme';
+import {enforceActOnUseLegacyStoreHook, mountWithTheme} from 'sentry-test/enzyme';
import {initializeOrg} from 'sentry-test/initializeOrg';
import {mountGlobalModal} from 'sentry-test/modal';
import {act} from 'sentry-test/reactTestingLibrary';
@@ -9,6 +9,8 @@ import ProjectsStore from 'app/stores/projectsStore';
import OrganizationGeneralSettings from 'app/views/settings/organizationGeneralSettings';
describe('OrganizationGeneralSettings', function () {
+ enforceActOnUseLegacyStoreHook();
+
let organization;
let routerContext;
const ENDPOINT = '/organizations/org-slug/';
@@ -60,13 +62,22 @@ describe('OrganizationGeneralSettings', function () {
await tick();
wrapper.update();
+
// Change slug
- wrapper
- .find('input[id="slug"]')
- .simulate('change', {target: {value: 'new-slug'}})
- .simulate('blur');
+ act(() => {
+ wrapper
+ .find('input[id="slug"]')
+ .simulate('change', {target: {value: 'new-slug'}})
+ .simulate('blur');
+ });
+
+ await tick();
+ wrapper.update();
+
+ act(() => {
+ wrapper.find('button[aria-label="Save"]').simulate('click');
+ });
- wrapper.find('button[aria-label="Save"]').simulate('click');
expect(mock).toHaveBeenCalledWith(
ENDPOINT,
expect.objectContaining({
|
87fd0bc38c450b507cd7d76fc663b682d3eeaf4f
|
2023-08-16 03:55:35
|
Alberto Leal
|
chore(hybrid-cloud): Update ApiGatewayTestCase test to be happy in split db world (#54791)
| false
|
Update ApiGatewayTestCase test to be happy in split db world (#54791)
|
chore
|
diff --git a/src/sentry/testutils/helpers/api_gateway.py b/src/sentry/testutils/helpers/api_gateway.py
index 9ebb857021c690..b81a5856fe5020 100644
--- a/src/sentry/testutils/helpers/api_gateway.py
+++ b/src/sentry/testutils/helpers/api_gateway.py
@@ -11,7 +11,7 @@
from rest_framework.response import Response
from sentry.api.base import control_silo_endpoint, region_silo_endpoint
-from sentry.api.bases.organization import OrganizationEndpoint
+from sentry.api.bases.organization import ControlSiloOrganizationEndpoint, OrganizationEndpoint
from sentry.api.endpoints.rpc import RpcServiceEndpoint
from sentry.testutils.cases import APITestCase
from sentry.testutils.region import override_regions
@@ -20,10 +20,10 @@
@control_silo_endpoint
-class ControlEndpoint(OrganizationEndpoint):
- permission_classes = (AllowAny,)
+class ControlEndpoint(ControlSiloOrganizationEndpoint):
+ permission_classes = (AllowAny,) # type: ignore
- def get(self, request, organization):
+ def get(self, request, organization, **kwargs):
return Response({"proxy": False})
|
65750ecfff2efcdd9e3fde3dd35e1b078e1a36b1
|
2023-08-09 00:20:17
|
Kev
|
feat(perf-issues): Add http overhead to perf issues frontend (#54384)
| false
|
Add http overhead to perf issues frontend (#54384)
|
feat
|
diff --git a/static/app/views/settings/projectPerformance/projectPerformance.tsx b/static/app/views/settings/projectPerformance/projectPerformance.tsx
index 9dbe0d09c8beef..aaf71b53d6c119 100644
--- a/static/app/views/settings/projectPerformance/projectPerformance.tsx
+++ b/static/app/views/settings/projectPerformance/projectPerformance.tsx
@@ -70,6 +70,7 @@ enum DetectorConfigAdmin {
LARGE_HTTP_PAYLOAD_ENABLED = 'large_http_payload_detection_enabled',
N_PLUS_ONE_API_CALLS_ENABLED = 'n_plus_one_api_calls_detection_enabled',
CONSECUTIVE_HTTP_ENABLED = 'consecutive_http_spans_detection_enabled',
+ HTTP_OVERHEAD_ENABLED = 'http_overhead_detection_enabled',
}
export enum DetectorConfigCustomer {
@@ -84,6 +85,7 @@ export enum DetectorConfigCustomer {
UNCOMPRESSED_ASSET_SIZE = 'uncompressed_asset_size_threshold',
CONSECUTIVE_DB_MIN_TIME_SAVED = 'consecutive_db_min_time_saved_threshold',
CONSECUTIVE_HTTP_MIN_TIME_SAVED = 'consecutive_http_spans_min_time_saved_threshold',
+ HTTP_OVERHEAD_REQUEST_DELAY = 'http_request_delay_threshold',
}
type RouteParams = {orgId: string; projectId: string};
@@ -423,6 +425,19 @@ class ProjectPerformance extends DeprecatedAsyncView<Props, State> {
},
}),
},
+ {
+ name: DetectorConfigAdmin.HTTP_OVERHEAD_ENABLED,
+ type: 'boolean',
+ label: t('HTTP/1.1 Overhead Enabled'),
+ defaultValue: true,
+ onChange: value =>
+ this.setState({
+ performance_issue_settings: {
+ ...this.state.performance_issue_settings,
+ [DetectorConfigAdmin.HTTP_OVERHEAD_ENABLED]: value,
+ },
+ }),
+ },
];
}
@@ -702,6 +717,28 @@ class ProjectPerformance extends DeprecatedAsyncView<Props, State> {
},
],
},
+ {
+ title: t('HTTP Overhead'),
+ fields: [
+ {
+ name: DetectorConfigCustomer.HTTP_OVERHEAD_REQUEST_DELAY,
+ type: 'range',
+ label: t('Request Delay'),
+ defaultValue: 500, // in ms
+ help: t(
+ 'Setting the value to 500ms, means that the HTTP request delay (wait time) will have to exceed 500ms for an HTTP Overhead issue to be created.'
+ ),
+ tickValues: [0, allowedDurationValues.slice(6, 17).length - 1],
+ showTickLabels: true,
+ allowedValues: allowedDurationValues.slice(6, 17),
+ disabled: !(
+ hasAccess && performanceSettings[DetectorConfigAdmin.HTTP_OVERHEAD_ENABLED]
+ ),
+ formatLabel: formatDuration,
+ disabledReason,
+ },
+ ],
+ },
];
};
|
2519ff13be2ea5248cbfe5c9a7efc1e072d116ba
|
2019-02-05 03:20:01
|
Jess MacQueen
|
fix(repos): Make it clear commit data will be deleted with repo
| false
|
Make it clear commit data will be deleted with repo
|
fix
|
diff --git a/src/sentry/static/sentry/app/components/repositoryRow.jsx b/src/sentry/static/sentry/app/components/repositoryRow.jsx
index 0d864f52be673e..61f17b60d61428 100644
--- a/src/sentry/static/sentry/app/components/repositoryRow.jsx
+++ b/src/sentry/static/sentry/app/components/repositoryRow.jsx
@@ -101,7 +101,9 @@ class RepositoryRow extends React.Component {
<Confirm
disabled={!hasAccess || (!isActive && repository.status !== 'disabled')}
onConfirm={this.deleteRepo}
- message={t('Are you sure you want to remove this repository?')}
+ message={t(
+ 'Are you sure you want to remove this repository? All associated commit data will be removed in addition to the repository.'
+ )}
>
<Button size="xsmall" icon="icon-trash" disabled={!hasAccess} />
</Confirm>
|
5d11add2e2f1f2b645360d74c6f2473d0f3d0c56
|
2025-03-22 03:08:47
|
Evan Purkhiser
|
ref(groupreference): Correctly find markdown linked group IDs (#87634)
| false
|
Correctly find markdown linked group IDs (#87634)
|
ref
|
diff --git a/src/sentry/utils/groupreference.py b/src/sentry/utils/groupreference.py
index 8b15865b535789..64bcdb8c9b7442 100644
--- a/src/sentry/utils/groupreference.py
+++ b/src/sentry/utils/groupreference.py
@@ -6,6 +6,8 @@
if TYPE_CHECKING:
from sentry.models.group import Group
+_markdown_strip_re = re.compile(r"\[([^]]+)\]\([^)]+\)", re.I)
+
_fixes_re = re.compile(
r"\b(?:Fix|Fixes|Fixed|Close|Closes|Closed|Resolve|Resolves|Resolved):?\s+([A-Za-z0-9_\-\s\,]+)\b",
re.I,
@@ -19,6 +21,12 @@ def find_referenced_groups(text: str | None, org_id: int) -> set[Group]:
if not text:
return set()
+ # XXX(epurkhiser): Currently we only strip markdown links from our text. It
+ # may make sense in the future to strip more, but we do offer users the
+ # ability to copy and paste sentry issues as markdown, so we should at
+ # least cover this case.
+ text = _markdown_strip_re.sub(r"\1", text)
+
results = set()
for fmatch in _fixes_re.finditer(text):
for smatch in _short_id_re.finditer(fmatch.group(1)):
diff --git a/tests/sentry/models/test_commit.py b/tests/sentry/models/test_commit.py
index 609a219da4ac0c..13b80a91543725 100644
--- a/tests/sentry/models/test_commit.py
+++ b/tests/sentry/models/test_commit.py
@@ -77,3 +77,21 @@ def test_multiple_matches_comma_separated(self):
assert len(groups) == 2
assert group in groups
assert group2 in groups
+
+ def test_markdown_links(self):
+ group = self.create_group()
+ group2 = self.create_group()
+
+ repo = Repository.objects.create(name="example", organization_id=self.group.organization.id)
+
+ commit = Commit.objects.create(
+ key=sha1(uuid4().hex.encode("utf-8")).hexdigest(),
+ repository_id=repo.id,
+ organization_id=group.organization.id,
+ message=f"Foo Biz\n\nFixes [{group.qualified_short_id}](https://sentry.io/), [{group2.qualified_short_id}](https://sentry.io/)",
+ )
+
+ groups = commit.find_referenced_groups()
+ assert len(groups) == 2
+ assert group in groups
+ assert group2 in groups
|
543f5278d09b17e11404f7fb174a0d2d0e571ee1
|
2021-11-03 18:50:50
|
Matej Minar
|
chore(deps): Upgrade [email protected] (#29656)
| false
|
Upgrade [email protected] (#29656)
|
chore
|
diff --git a/package.json b/package.json
index 9bcc948ff0f441..4d1b6c2178ce0b 100644
--- a/package.json
+++ b/package.json
@@ -158,7 +158,7 @@
"csstype": "^3.0.8",
"enzyme": "3.11.0",
"eslint": "5.11.1",
- "eslint-config-sentry-app": "1.62.0",
+ "eslint-config-sentry-app": "1.64.0",
"eslint-plugin-simple-import-sort": "^6.0.0",
"html-webpack-plugin": "^5.3.2",
"jest": "27.0.6",
diff --git a/tests/js/spec/components/events/interfaces/threadsV2.spec.tsx b/tests/js/spec/components/events/interfaces/threadsV2.spec.tsx
index cdfebe283d14c7..342d62d83fd4e5 100644
--- a/tests/js/spec/components/events/interfaces/threadsV2.spec.tsx
+++ b/tests/js/spec/components/events/interfaces/threadsV2.spec.tsx
@@ -265,10 +265,10 @@ describe('ThreadsV2', function () {
fireEvent.click(screen.getByRole('button', {name: 'Sort By Recent first'}));
expect(screen.queryAllByLabelText('Sort option')).toHaveLength(2);
- expect(screen.queryAllByLabelText('Sort option')[0].textContent).toBe(
+ expect(screen.queryAllByLabelText('Sort option')[0]).toHaveTextContent(
'Recent first'
);
- expect(screen.queryAllByLabelText('Sort option')[1].textContent).toBe(
+ expect(screen.queryAllByLabelText('Sort option')[1]).toHaveTextContent(
'Recent last'
);
@@ -305,7 +305,7 @@ describe('ThreadsV2', function () {
expect(screen.queryAllByLabelText('Display option')).toHaveLength(2);
const displayOption0 = screen.queryAllByLabelText('Display option')[0];
- expect(displayOption0.textContent).toBe('Minified');
+ expect(displayOption0).toHaveTextContent('Minified');
expect(within(displayOption0).getByRole('checkbox')).not.toBeChecked();
expect(within(displayOption0).getByRole('checkbox')).toHaveAttribute(
'aria-disabled',
@@ -319,7 +319,7 @@ describe('ThreadsV2', function () {
).toBeInTheDocument();
const displayOption1 = screen.queryAllByLabelText('Display option')[1];
- expect(displayOption1.textContent).toBe('Full Stack Trace');
+ expect(displayOption1).toHaveTextContent('Full Stack Trace');
expect(within(displayOption1).getByRole('checkbox')).toBeChecked();
expect(within(displayOption1).getByRole('checkbox')).toHaveAttribute(
'aria-disabled',
@@ -922,10 +922,10 @@ describe('ThreadsV2', function () {
fireEvent.click(screen.getByRole('button', {name: 'Sort By Recent first'}));
expect(screen.queryAllByLabelText('Sort option')).toHaveLength(2);
- expect(screen.queryAllByLabelText('Sort option')[0].textContent).toBe(
+ expect(screen.queryAllByLabelText('Sort option')[0]).toHaveTextContent(
'Recent first'
);
- expect(screen.queryAllByLabelText('Sort option')[1].textContent).toBe(
+ expect(screen.queryAllByLabelText('Sort option')[1]).toHaveTextContent(
'Recent last'
);
@@ -961,7 +961,7 @@ describe('ThreadsV2', function () {
expect(screen.queryAllByLabelText('Display option')).toHaveLength(5);
const displayOption0 = screen.queryAllByLabelText('Display option')[0];
- expect(displayOption0.textContent).toBe('Unsymbolicated');
+ expect(displayOption0).toHaveTextContent('Unsymbolicated');
expect(within(displayOption0).getByRole('checkbox')).not.toBeChecked();
expect(within(displayOption0).getByRole('checkbox')).toHaveAttribute(
'aria-disabled',
@@ -969,7 +969,7 @@ describe('ThreadsV2', function () {
);
const displayOption1 = screen.queryAllByLabelText('Display option')[1];
- expect(displayOption1.textContent).toBe('Absolute Addresses');
+ expect(displayOption1).toHaveTextContent('Absolute Addresses');
expect(within(displayOption1).getByRole('checkbox')).not.toBeChecked();
expect(within(displayOption1).getByRole('checkbox')).toHaveAttribute(
'aria-disabled',
@@ -977,7 +977,7 @@ describe('ThreadsV2', function () {
);
const displayOption2 = screen.queryAllByLabelText('Display option')[2];
- expect(displayOption2.textContent).toBe('Absolute File Paths');
+ expect(displayOption2).toHaveTextContent('Absolute File Paths');
expect(within(displayOption2).getByRole('checkbox')).not.toBeChecked();
expect(within(displayOption2).getByRole('checkbox')).toHaveAttribute(
'aria-disabled',
@@ -985,7 +985,7 @@ describe('ThreadsV2', function () {
);
const displayOption3 = screen.queryAllByLabelText('Display option')[3];
- expect(displayOption3.textContent).toBe('Verbose Function Names');
+ expect(displayOption3).toHaveTextContent('Verbose Function Names');
expect(within(displayOption3).getByRole('checkbox')).not.toBeChecked();
expect(within(displayOption3).getByRole('checkbox')).toHaveAttribute(
'aria-disabled',
@@ -993,7 +993,7 @@ describe('ThreadsV2', function () {
);
const displayOption4 = screen.queryAllByLabelText('Display option')[4];
- expect(displayOption4.textContent).toBe('Full Stack Trace');
+ expect(displayOption4).toHaveTextContent('Full Stack Trace');
expect(within(displayOption4).getByRole('checkbox')).toBeChecked();
expect(within(displayOption4).getByRole('checkbox')).toHaveAttribute(
'aria-disabled',
diff --git a/tests/js/spec/views/organizationDetails/organizationsDetails.spec.jsx b/tests/js/spec/views/organizationDetails/organizationsDetails.spec.jsx
index 311ea881f40d41..52e8b3b94d116b 100644
--- a/tests/js/spec/views/organizationDetails/organizationsDetails.spec.jsx
+++ b/tests/js/spec/views/organizationDetails/organizationsDetails.spec.jsx
@@ -113,7 +113,7 @@ describe('OrganizationDetails', function () {
);
expect(mistakeText).toBeInTheDocument();
- expect(screen.queryByLabelText('Restore Organization')).toBeNull();
+ expect(screen.queryByLabelText('Restore Organization')).not.toBeInTheDocument();
});
});
@@ -142,6 +142,6 @@ describe('OrganizationDetails', function () {
);
expect(inProgress).toBeInTheDocument();
- expect(screen.queryByLabelText('Restore Organization')).toBeNull();
+ expect(screen.queryByLabelText('Restore Organization')).not.toBeInTheDocument();
});
});
diff --git a/yarn.lock b/yarn.lock
index b9229d1c2a2262..3bce2177705690 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -1187,7 +1187,7 @@
dependencies:
regenerator-runtime "^0.13.2"
-"@babel/runtime@^7.0.0", "@babel/runtime@^7.1.2", "@babel/runtime@^7.10.2", "@babel/runtime@^7.12.5", "@babel/runtime@^7.13.10", "@babel/runtime@^7.14.0", "@babel/runtime@^7.3.1", "@babel/runtime@^7.3.4", "@babel/runtime@^7.4.4", "@babel/runtime@^7.5.0", "@babel/runtime@^7.5.5", "@babel/runtime@^7.7.2", "@babel/runtime@^7.7.6", "@babel/runtime@^7.8.4", "@babel/runtime@^7.8.7", "@babel/runtime@^7.9.2", "@babel/runtime@~7.15.4":
+"@babel/runtime@^7.0.0", "@babel/runtime@^7.1.2", "@babel/runtime@^7.10.2", "@babel/runtime@^7.12.5", "@babel/runtime@^7.13.10", "@babel/runtime@^7.14.0", "@babel/runtime@^7.3.1", "@babel/runtime@^7.3.4", "@babel/runtime@^7.4.4", "@babel/runtime@^7.5.0", "@babel/runtime@^7.5.5", "@babel/runtime@^7.7.2", "@babel/runtime@^7.7.6", "@babel/runtime@^7.8.4", "@babel/runtime@^7.8.7", "@babel/runtime@^7.9.2", "@babel/runtime@^7.9.6", "@babel/runtime@~7.15.4":
version "7.15.4"
resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.15.4.tgz#fd17d16bfdf878e6dd02d19753a39fa8a8d9c84a"
integrity sha512-99catp6bHCaxr4sJ/DbTGgHS4+Rs2RVd2g7iOap6SLGPDknRK9ztKNsE/Fg6QhSeh1FGE5f6gHGQmvvn3I3xhw==
@@ -2934,6 +2934,20 @@
lz-string "^1.4.4"
pretty-format "^27.0.2"
+"@testing-library/dom@^7.28.1":
+ version "7.31.2"
+ resolved "https://registry.yarnpkg.com/@testing-library/dom/-/dom-7.31.2.tgz#df361db38f5212b88555068ab8119f5d841a8c4a"
+ integrity sha512-3UqjCpey6HiTZT92vODYLPxTBWlM8ZOOjr3LX5F37/VRipW2M1kX6I/Cm4VXzteZqfGfagg8yXywpcOgQBlNsQ==
+ dependencies:
+ "@babel/code-frame" "^7.10.4"
+ "@babel/runtime" "^7.12.5"
+ "@types/aria-query" "^4.2.0"
+ aria-query "^4.2.2"
+ chalk "^4.1.0"
+ dom-accessibility-api "^0.5.6"
+ lz-string "^1.4.4"
+ pretty-format "^26.6.2"
+
"@testing-library/jest-dom@^5.14.1":
version "5.14.1"
resolved "https://registry.yarnpkg.com/@testing-library/jest-dom/-/jest-dom-5.14.1.tgz#8501e16f1e55a55d675fe73eecee32cdaddb9766"
@@ -6675,16 +6689,16 @@ [email protected]:
dependencies:
get-stdin "^6.0.0"
[email protected]:
- version "1.62.0"
- resolved "https://registry.yarnpkg.com/eslint-config-sentry-app/-/eslint-config-sentry-app-1.62.0.tgz#02367bf8ece669e8a5bba858d1ccd081ace78dd8"
- integrity sha512-6W0aM8MSgrMIHfLVoCzg7GPxRgdz57jksUIqhgivq2sBORxYvkF9E6BCCg3ysjunQU6iWarWC+9uMFCU3Ag4Xg==
[email protected]:
+ version "1.64.0"
+ resolved "https://registry.yarnpkg.com/eslint-config-sentry-app/-/eslint-config-sentry-app-1.64.0.tgz#7d8605c0f5f24ae1f093eaded88022739cef1ca2"
+ integrity sha512-CV2YIiaGOQV3B3HY4c7BJ1HvYFafFcdWQwsuZJtylinay28eE/vU7RpyDhPgzMKTc5/4sCGaAPuW9PxHGdQAQA==
dependencies:
"@typescript-eslint/eslint-plugin" "^4.31.0"
"@typescript-eslint/parser" "^4.31.0"
eslint-config-prettier "6.3.0"
- eslint-config-sentry "^1.62.0"
- eslint-config-sentry-react "^1.62.0"
+ eslint-config-sentry "^1.64.0"
+ eslint-config-sentry-react "^1.64.0"
eslint-import-resolver-typescript "^2.4.0"
eslint-import-resolver-webpack "^0.13.1"
eslint-plugin-emotion "^10.0.27"
@@ -6692,20 +6706,21 @@ [email protected]:
eslint-plugin-jest "22.17.0"
eslint-plugin-prettier "3.1.1"
eslint-plugin-react "7.15.1"
- eslint-plugin-sentry "^1.62.0"
+ eslint-plugin-sentry "^1.64.0"
eslint-plugin-simple-import-sort "^7.0.0"
-eslint-config-sentry-react@^1.62.0:
- version "1.62.0"
- resolved "https://registry.yarnpkg.com/eslint-config-sentry-react/-/eslint-config-sentry-react-1.62.0.tgz#3699b8fa881bb4624f046b3679a7590257c00b3f"
- integrity sha512-tLbCDXPl3+mp8HACQpF44OSzZKKQNhxv8zxKqVVVuif2OHFZu/+XfMdWS8EuuUKyGpmTgkW7HfYSkIKznXPb/w==
+eslint-config-sentry-react@^1.64.0:
+ version "1.64.0"
+ resolved "https://registry.yarnpkg.com/eslint-config-sentry-react/-/eslint-config-sentry-react-1.64.0.tgz#460f8994bdb8fc0e300a112e488f54515c8bcdf9"
+ integrity sha512-VBtrzYUjAHvJdA3ObR0jbk4fk2DrMniWKp+GTF4bQfT3pVIY33ng8tZ3s4iEfSMrDSGVfhOw3lwFjYfXmHaCgg==
dependencies:
- eslint-config-sentry "^1.62.0"
+ eslint-config-sentry "^1.64.0"
+ eslint-plugin-jest-dom "^3.9.2"
-eslint-config-sentry@^1.62.0:
- version "1.62.0"
- resolved "https://registry.yarnpkg.com/eslint-config-sentry/-/eslint-config-sentry-1.62.0.tgz#b57a08f45922c9528aa17dcfc3950eeb2fa13ac6"
- integrity sha512-cxt/MaGl65TLzvDszVmLICSvxssoHZ3UVXD+fJ7oAygqnWuP6+vMvwsgi322FDOe/OgCHU+xrVkjm67vhtuQEw==
+eslint-config-sentry@^1.64.0:
+ version "1.64.0"
+ resolved "https://registry.yarnpkg.com/eslint-config-sentry/-/eslint-config-sentry-1.64.0.tgz#6db744b09d238915045e9868cbd07844c4ea618f"
+ integrity sha512-noCNCypHBnS6v4CuMI9WURGzwijhIvUsVLb3tIL1OVD56xOf1SMYSAkjPUKvQzvS9qLTiUf9UiTu23qVVL+4vA==
eslint-import-resolver-node@^0.3.4:
version "0.3.4"
@@ -6777,6 +6792,15 @@ eslint-plugin-import@^2.23.4:
resolve "^1.20.0"
tsconfig-paths "^3.9.0"
+eslint-plugin-jest-dom@^3.9.2:
+ version "3.9.2"
+ resolved "https://registry.yarnpkg.com/eslint-plugin-jest-dom/-/eslint-plugin-jest-dom-3.9.2.tgz#2cc200cabb17d1f5535afad9b49d0ca41b2f05eb"
+ integrity sha512-DKNW6nxYkBvwv36WcYFxapCalGjOGSWUu5PREpDVuXGbEns3S5jhr+mZ5W2N6MxbOWw/2U61C1JVLH31gwVjOQ==
+ dependencies:
+ "@babel/runtime" "^7.9.6"
+ "@testing-library/dom" "^7.28.1"
+ requireindex "^1.2.0"
+
[email protected]:
version "22.17.0"
resolved "https://registry.yarnpkg.com/eslint-plugin-jest/-/eslint-plugin-jest-22.17.0.tgz#dc170ec8369cd1bff9c5dd8589344e3f73c88cf6"
@@ -6806,10 +6830,10 @@ [email protected]:
prop-types "^15.7.2"
resolve "^1.12.0"
-eslint-plugin-sentry@^1.62.0:
- version "1.62.0"
- resolved "https://registry.yarnpkg.com/eslint-plugin-sentry/-/eslint-plugin-sentry-1.62.0.tgz#49c24a12b67b0181086fc1de8b316bdb352acb32"
- integrity sha512-UmR/X2XUUxnBpXgx9/UfQsQqXlnymurFOJk+PQCu29oUlO+sR6spXhJmUV/HrjJqRDOIyoq1BdAauJPS2wPwqA==
+eslint-plugin-sentry@^1.64.0:
+ version "1.64.0"
+ resolved "https://registry.yarnpkg.com/eslint-plugin-sentry/-/eslint-plugin-sentry-1.64.0.tgz#aea659b4bdda5140512e569636f47053b91ecaf1"
+ integrity sha512-OcA53u7sBLuZwaFpkHh7ODLJq0cQvB3pIGLIukY/dmetHZVDNHYMujOVVDiJSlTc6U535SLC+hb/qJipHpu+QQ==
dependencies:
requireindex "~1.1.0"
@@ -12810,6 +12834,11 @@ require-uncached@^1.0.3:
caller-path "^0.1.0"
resolve-from "^1.0.0"
+requireindex@^1.2.0:
+ version "1.2.0"
+ resolved "https://registry.yarnpkg.com/requireindex/-/requireindex-1.2.0.tgz#3463cdb22ee151902635aa6c9535d4de9c2ef1ef"
+ integrity sha512-L9jEkOi3ASd9PYit2cwRfyppc9NoABujTP8/5gFcbERmo5jUoAKovIC3fsF17pkTnGsrByysqX+Kxd2OTNI1ww==
+
requireindex@~1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/requireindex/-/requireindex-1.1.0.tgz#e5404b81557ef75db6e49c5a72004893fe03e162"
|
0c88d7b1fb72d707398e8c1d039030fb86052f09
|
2021-12-15 09:51:33
|
Evan Purkhiser
|
ref(js): Remove unused getEndpoint (#30659)
| false
|
Remove unused getEndpoint (#30659)
|
ref
|
diff --git a/static/app/components/asyncComponent.tsx b/static/app/components/asyncComponent.tsx
index 388e87ae11ed31..50b610a4da625f 100644
--- a/static/app/components/asyncComponent.tsx
+++ b/static/app/components/asyncComponent.tsx
@@ -338,24 +338,6 @@ export default class AsyncComponent<
this.onRequestError(error, args);
}
- /**
- * @deprecated use getEndpoints
- */
- getEndpointParams() {
- // eslint-disable-next-line no-console
- console.warn('getEndpointParams is deprecated');
- return {};
- }
-
- /**
- * @deprecated use getEndpoints
- */
- getEndpoint() {
- // eslint-disable-next-line no-console
- console.warn('getEndpoint is deprecated');
- return null;
- }
-
/**
* Return a list of endpoint queries to make.
*
@@ -364,11 +346,7 @@ export default class AsyncComponent<
* ]
*/
getEndpoints(): Array<[string, string, any?, any?]> {
- const endpoint = this.getEndpoint();
- if (!endpoint) {
- return [];
- }
- return [['data', endpoint, this.getEndpointParams()]];
+ return [];
}
renderSearchInput({stateKey, url, ...props}: RenderSearchInputArgs) {
|
70c361f6873b0a4d943f6aeae3e071484fca1cd3
|
2024-05-15 18:42:05
|
George Gritsouk
|
ref(insights): Declare module base URLs as constants (#70861)
| false
|
Declare module base URLs as constants (#70861)
|
ref
|
diff --git a/static/app/views/aiMonitoring/aiMonitoringDetailsPage.tsx b/static/app/views/aiMonitoring/aiMonitoringDetailsPage.tsx
index 3720c0ef13700a..30e663bc172c83 100644
--- a/static/app/views/aiMonitoring/aiMonitoringDetailsPage.tsx
+++ b/static/app/views/aiMonitoring/aiMonitoringDetailsPage.tsx
@@ -21,6 +21,7 @@ import {
TotalTokensUsedChart,
} from 'sentry/views/aiMonitoring/aiMonitoringCharts';
import {PipelineSpansTable} from 'sentry/views/aiMonitoring/pipelineSpansTable';
+import {BASE_URL} from 'sentry/views/aiMonitoring/settings';
import {MetricReadout} from 'sentry/views/performance/metricReadout';
import * as ModuleLayout from 'sentry/views/performance/moduleLayout';
import {ModulePageProviders} from 'sentry/views/performance/modulePageProviders';
@@ -178,7 +179,7 @@ function PageWithProviders({params}: Props) {
return (
<ModulePageProviders
title={[spanDescription ?? t('(no name)'), t('Pipeline Details')].join(' — ')}
- baseURL="/ai-monitoring/"
+ baseURL={BASE_URL}
features="ai-analytics"
>
<AiMonitoringPage params={params} />
diff --git a/static/app/views/aiMonitoring/landing.tsx b/static/app/views/aiMonitoring/landing.tsx
index 12138da8b0b098..298a687c8fadfc 100644
--- a/static/app/views/aiMonitoring/landing.tsx
+++ b/static/app/views/aiMonitoring/landing.tsx
@@ -17,6 +17,7 @@ import {
} from 'sentry/views/aiMonitoring/aiMonitoringCharts';
import {AIMonitoringOnboarding} from 'sentry/views/aiMonitoring/onboarding';
import {PipelinesTable} from 'sentry/views/aiMonitoring/PipelinesTable';
+import {BASE_URL} from 'sentry/views/aiMonitoring/settings';
import {useOnboardingProject} from 'sentry/views/performance/browser/webVitals/utils/useOnboardingProject';
import * as ModuleLayout from 'sentry/views/performance/moduleLayout';
import {ModulePageProviders} from 'sentry/views/performance/modulePageProviders';
@@ -92,7 +93,7 @@ function PageWithProviders() {
return (
<ModulePageProviders
title={t('AI Monitoring')}
- baseURL="/ai-monitoring/"
+ baseURL={BASE_URL}
features="ai-analytics"
>
<AiMonitoringPage />
diff --git a/static/app/views/aiMonitoring/settings.ts b/static/app/views/aiMonitoring/settings.ts
new file mode 100644
index 00000000000000..c0626c3bdab8ee
--- /dev/null
+++ b/static/app/views/aiMonitoring/settings.ts
@@ -0,0 +1,4 @@
+import {t} from 'sentry/locale';
+
+export const MODULE_TITLE = t('AI Monitoring');
+export const BASE_URL = '/ai-monitoring';
diff --git a/static/app/views/performance/browser/resources/index.tsx b/static/app/views/performance/browser/resources/index.tsx
index e43e7ca7f9b400..bb74f413042224 100644
--- a/static/app/views/performance/browser/resources/index.tsx
+++ b/static/app/views/performance/browser/resources/index.tsx
@@ -19,6 +19,7 @@ import ResourceView, {
DEFAULT_RESOURCE_TYPES,
FilterOptionsContainer,
} from 'sentry/views/performance/browser/resources/resourceView';
+import {BASE_URL} from 'sentry/views/performance/browser/resources/settings';
import {
BrowserStarfishFields,
useResourceModuleFilters,
@@ -91,7 +92,7 @@ function PageWithProviders() {
return (
<ModulePageProviders
title={[t('Performance'), t('Resources')].join(' — ')}
- baseURL="/performance/browser/resources"
+ baseURL={`/performance/${BASE_URL}`}
features="spans-first-ui"
>
<ResourcesLandingPage />
diff --git a/static/app/views/performance/browser/resources/resourceSummaryPage/index.tsx b/static/app/views/performance/browser/resources/resourceSummaryPage/index.tsx
index 8a586366aa268b..08bda4a6a0244f 100644
--- a/static/app/views/performance/browser/resources/resourceSummaryPage/index.tsx
+++ b/static/app/views/performance/browser/resources/resourceSummaryPage/index.tsx
@@ -21,6 +21,7 @@ import ResourceSummaryCharts from 'sentry/views/performance/browser/resources/re
import ResourceSummaryTable from 'sentry/views/performance/browser/resources/resourceSummaryPage/resourceSummaryTable';
import SampleImages from 'sentry/views/performance/browser/resources/resourceSummaryPage/sampleImages';
import {FilterOptionsContainer} from 'sentry/views/performance/browser/resources/resourceView';
+import {BASE_URL} from 'sentry/views/performance/browser/resources/settings';
import {IMAGE_FILE_EXTENSIONS} from 'sentry/views/performance/browser/resources/shared/constants';
import RenderBlockingSelector from 'sentry/views/performance/browser/resources/shared/renderBlockingSelector';
import {ResourceSpanOps} from 'sentry/views/performance/browser/resources/shared/types';
@@ -160,7 +161,7 @@ function PageWithProviders() {
return (
<ModulePageProviders
title={[t('Performance'), t('Resources'), t('Resource Summary')].join(' — ')}
- baseURL="/performance/browser/resources"
+ baseURL={`/performance/${BASE_URL}`}
features="spans-first-ui"
>
<ResourceSummary />
diff --git a/static/app/views/performance/browser/resources/settings.ts b/static/app/views/performance/browser/resources/settings.ts
new file mode 100644
index 00000000000000..32a12ee41f17cd
--- /dev/null
+++ b/static/app/views/performance/browser/resources/settings.ts
@@ -0,0 +1,4 @@
+import {t} from 'sentry/locale';
+
+export const MODULE_TITLE = t('Resources');
+export const BASE_URL = 'browser/resources';
diff --git a/static/app/views/performance/browser/webVitals/pageOverview.tsx b/static/app/views/performance/browser/webVitals/pageOverview.tsx
index eda1d24059b968..3cc672d0f1333b 100644
--- a/static/app/views/performance/browser/webVitals/pageOverview.tsx
+++ b/static/app/views/performance/browser/webVitals/pageOverview.tsx
@@ -37,6 +37,7 @@ import {
import WebVitalMeters from 'sentry/views/performance/browser/webVitals/components/webVitalMeters';
import {PageOverviewWebVitalsDetailPanel} from 'sentry/views/performance/browser/webVitals/pageOverviewWebVitalsDetailPanel';
import {PageSamplePerformanceTable} from 'sentry/views/performance/browser/webVitals/pageSamplePerformanceTable';
+import {BASE_URL} from 'sentry/views/performance/browser/webVitals/settings';
import {useProjectRawWebVitalsQuery} from 'sentry/views/performance/browser/webVitals/utils/queries/rawWebVitalsQueries/useProjectRawWebVitalsQuery';
import {calculatePerformanceScoreFromStoredTableDataRow} from 'sentry/views/performance/browser/webVitals/utils/queries/storedScoreQueries/calculatePerformanceScoreFromStored';
import {useProjectWebVitalsScoresQuery} from 'sentry/views/performance/browser/webVitals/utils/queries/storedScoreQueries/useProjectWebVitalsScoresQuery';
@@ -307,7 +308,7 @@ function PageWithProviders() {
return (
<ModulePageProviders
title={[t('Performance'), t('Web Vitals')].join(' — ')}
- baseURL="/performance/browser/pageloads"
+ baseURL={`/performance/${BASE_URL}`}
features="spans-first-ui"
>
<PageOverview />
diff --git a/static/app/views/performance/browser/webVitals/settings.ts b/static/app/views/performance/browser/webVitals/settings.ts
index ebffe13cb1969a..80cefe3548684d 100644
--- a/static/app/views/performance/browser/webVitals/settings.ts
+++ b/static/app/views/performance/browser/webVitals/settings.ts
@@ -1,2 +1,7 @@
+import {t} from 'sentry/locale';
+
+export const MODULE_TITLE = t('Web Vitals');
+export const BASE_URL = 'browser/pageloads';
+
export const USE_STORED_SCORES = false;
export const REPLACE_FID_WITH_INP = false;
diff --git a/static/app/views/performance/browser/webVitals/webVitalsLandingPage.tsx b/static/app/views/performance/browser/webVitals/webVitalsLandingPage.tsx
index 7deb54efb5f07d..65d5fae10ed93f 100644
--- a/static/app/views/performance/browser/webVitals/webVitalsLandingPage.tsx
+++ b/static/app/views/performance/browser/webVitals/webVitalsLandingPage.tsx
@@ -27,6 +27,7 @@ import {FID_DEPRECATION_DATE} from 'sentry/views/performance/browser/webVitals/c
import WebVitalMeters from 'sentry/views/performance/browser/webVitals/components/webVitalMeters';
import {PagePerformanceTable} from 'sentry/views/performance/browser/webVitals/pagePerformanceTable';
import {PerformanceScoreChart} from 'sentry/views/performance/browser/webVitals/performanceScoreChart';
+import {BASE_URL} from 'sentry/views/performance/browser/webVitals/settings';
import {useProjectRawWebVitalsQuery} from 'sentry/views/performance/browser/webVitals/utils/queries/rawWebVitalsQueries/useProjectRawWebVitalsQuery';
import {calculatePerformanceScoreFromStoredTableDataRow} from 'sentry/views/performance/browser/webVitals/utils/queries/storedScoreQueries/calculatePerformanceScoreFromStored';
import {useProjectWebVitalsScoresQuery} from 'sentry/views/performance/browser/webVitals/utils/queries/storedScoreQueries/useProjectWebVitalsScoresQuery';
@@ -182,7 +183,7 @@ function PageWithProviders() {
return (
<ModulePageProviders
title={[t('Performance'), t('Web Vitals')].join(' — ')}
- baseURL="/performance/browser/pageloads"
+ baseURL={`/performance/${BASE_URL}`}
features="spans-first-ui"
>
<WebVitalsLandingPage />
diff --git a/static/app/views/performance/cache/cacheLandingPage.tsx b/static/app/views/performance/cache/cacheLandingPage.tsx
index 65e9ef4a559fd0..d33975e1b3e950 100644
--- a/static/app/views/performance/cache/cacheLandingPage.tsx
+++ b/static/app/views/performance/cache/cacheLandingPage.tsx
@@ -23,7 +23,7 @@ import {Referrer} from 'sentry/views/performance/cache/referrers';
import {CacheSamplePanel} from 'sentry/views/performance/cache/samplePanel/samplePanel';
import {
BASE_FILTERS,
- CACHE_BASE_URL,
+ BASE_URL,
MODULE_TITLE,
RELEASE_LEVEL,
} from 'sentry/views/performance/cache/settings';
@@ -206,7 +206,7 @@ function PageWithProviders() {
return (
<ModulePageProviders
title={[t('Performance'), MODULE_TITLE].join(' — ')}
- baseURL={CACHE_BASE_URL}
+ baseURL={`/performance/${BASE_URL}`}
features="performance-cache-view"
>
<CacheLandingPage />
diff --git a/static/app/views/performance/cache/settings.ts b/static/app/views/performance/cache/settings.ts
index 10f82cc59437b0..4117e60e20982a 100644
--- a/static/app/views/performance/cache/settings.ts
+++ b/static/app/views/performance/cache/settings.ts
@@ -2,6 +2,9 @@ import type {BadgeType} from 'sentry/components/badge/featureBadge';
import {t} from 'sentry/locale';
import type {SpanMetricsQueryFilters} from 'sentry/views/starfish/types';
+export const MODULE_TITLE = t('Cache');
+export const BASE_URL = 'cache';
+
export const RELEASE_LEVEL: BadgeType = 'alpha';
// NOTE: Awkward typing, but without it `RELEASE_LEVEL` is narrowed and the comparison is not allowed
@@ -11,11 +14,9 @@ export const releaseLevelAsBadgeProps = {
isNew: (RELEASE_LEVEL as BadgeType) === 'new',
};
-export const MODULE_TITLE = t('Cache');
-
export const CHART_HEIGHT = 160;
-export const CACHE_BASE_URL = '/performance/cache';
+export const CACHE_BASE_URL = `/performance/${BASE_URL}`;
export const BASE_FILTERS: SpanMetricsQueryFilters = {
'span.op': 'cache.get_item', // TODO - add more span ops as they become available, we can't use span.module because db.redis is also `cache`
diff --git a/static/app/views/performance/database/databaseLandingPage.tsx b/static/app/views/performance/database/databaseLandingPage.tsx
index 5627a4527a4e96..67dd45514f24aa 100644
--- a/static/app/views/performance/database/databaseLandingPage.tsx
+++ b/static/app/views/performance/database/databaseLandingPage.tsx
@@ -23,6 +23,7 @@ import {useOnboardingProject} from 'sentry/views/performance/browser/webVitals/u
import {DurationChart} from 'sentry/views/performance/database/durationChart';
import {NoDataMessage} from 'sentry/views/performance/database/noDataMessage';
import {isAValidSort, QueriesTable} from 'sentry/views/performance/database/queriesTable';
+import {BASE_URL} from 'sentry/views/performance/database/settings';
import {ThroughputChart} from 'sentry/views/performance/database/throughputChart';
import {useSelectedDurationAggregate} from 'sentry/views/performance/database/useSelectedDurationAggregate';
import * as ModuleLayout from 'sentry/views/performance/moduleLayout';
@@ -269,7 +270,7 @@ function PageWithProviders() {
return (
<ModulePageProviders
title={[t('Performance'), t('Database')].join(' — ')}
- baseURL="/performance/database"
+ baseURL={`/performance/${BASE_URL}`}
features="spans-first-ui"
>
<DatabaseLandingPage />
diff --git a/static/app/views/performance/database/databaseSpanSummaryPage.tsx b/static/app/views/performance/database/databaseSpanSummaryPage.tsx
index e66cdd7e9128f4..5a1ea1ca01610e 100644
--- a/static/app/views/performance/database/databaseSpanSummaryPage.tsx
+++ b/static/app/views/performance/database/databaseSpanSummaryPage.tsx
@@ -20,6 +20,7 @@ import {normalizeUrl} from 'sentry/utils/withDomainRequired';
import {DurationChart} from 'sentry/views/performance/database/durationChart';
import {isAValidSort} from 'sentry/views/performance/database/queriesTable';
import {QueryTransactionsTable} from 'sentry/views/performance/database/queryTransactionsTable';
+import {BASE_URL} from 'sentry/views/performance/database/settings';
import {ThroughputChart} from 'sentry/views/performance/database/throughputChart';
import {useSelectedDurationAggregate} from 'sentry/views/performance/database/useSelectedDurationAggregate';
import {MetricReadout} from 'sentry/views/performance/metricReadout';
@@ -314,7 +315,7 @@ function PageWithProviders(props) {
return (
<ModulePageProviders
title={[t('Performance'), t('Database'), t('Query Summary')].join(' — ')}
- baseURL="/performance/database"
+ baseURL={`/performance/${BASE_URL}`}
features="spans-first-ui"
>
<DatabaseSpanSummaryPage {...props} />
diff --git a/static/app/views/performance/database/settings.ts b/static/app/views/performance/database/settings.ts
index 105c197f718033..e6da078caef386 100644
--- a/static/app/views/performance/database/settings.ts
+++ b/static/app/views/performance/database/settings.ts
@@ -8,8 +8,12 @@ import {
TWENTY_FOUR_HOURS,
TWO_WEEKS,
} from 'sentry/components/charts/utils';
+import {t} from 'sentry/locale';
import type {Aggregate} from 'sentry/views/starfish/types';
+export const MODULE_TITLE = t('Queries');
+export const BASE_URL = 'database';
+
export const MIN_SDK_VERSION_BY_PLATFORM: {[platform: string]: string} = {
'sentry.python': '1.29.2',
'sentry.javascript': '7.63.0',
diff --git a/static/app/views/performance/http/httpDomainSummaryPage.tsx b/static/app/views/performance/http/httpDomainSummaryPage.tsx
index bbd6f3b4f1508c..1b8ea41ce5c37f 100644
--- a/static/app/views/performance/http/httpDomainSummaryPage.tsx
+++ b/static/app/views/performance/http/httpDomainSummaryPage.tsx
@@ -34,6 +34,7 @@ import {HTTPSamplesPanel} from 'sentry/views/performance/http/httpSamplesPanel';
import {Referrer} from 'sentry/views/performance/http/referrers';
import {
BASE_FILTERS,
+ BASE_URL,
MODULE_TITLE,
NULL_DOMAIN_DESCRIPTION,
RELEASE_LEVEL,
@@ -357,7 +358,7 @@ const MetricsRibbon = styled('div')`
function PageWithProviders() {
return (
<ModulePageProviders
- baseURL="/performance/http"
+ baseURL={`/performance/${BASE_URL}`}
title={[t('Performance'), MODULE_TITLE, t('Domain Summary')].join(' — ')}
features="spans-first-ui"
>
diff --git a/static/app/views/performance/http/httpLandingPage.tsx b/static/app/views/performance/http/httpLandingPage.tsx
index 537cf4fb95dfa5..ec367db9ca014b 100644
--- a/static/app/views/performance/http/httpLandingPage.tsx
+++ b/static/app/views/performance/http/httpLandingPage.tsx
@@ -25,6 +25,7 @@ import {ThroughputChart} from 'sentry/views/performance/http/charts/throughputCh
import {Referrer} from 'sentry/views/performance/http/referrers';
import {
BASE_FILTERS,
+ BASE_URL,
MODULE_TITLE,
RELEASE_LEVEL,
} from 'sentry/views/performance/http/settings';
@@ -254,7 +255,7 @@ function PageWithProviders() {
return (
<ModulePageProviders
title={[t('Performance'), MODULE_TITLE].join(' — ')}
- baseURL="/performance/http"
+ baseURL={`/performance/${BASE_URL}`}
features="spans-first-ui"
>
<HTTPLandingPage />
diff --git a/static/app/views/performance/http/settings.ts b/static/app/views/performance/http/settings.ts
index 10524cea7a63ac..f3e35044f0d70a 100644
--- a/static/app/views/performance/http/settings.ts
+++ b/static/app/views/performance/http/settings.ts
@@ -3,6 +3,7 @@ import {t} from 'sentry/locale';
import {ModuleName} from 'sentry/views/starfish/types';
export const MODULE_TITLE = t('Requests');
+export const BASE_URL = 'http';
export const NULL_DOMAIN_DESCRIPTION = t('Unknown Domain');
diff --git a/static/app/views/performance/landing/widgets/widgets/lineChartListWidget.tsx b/static/app/views/performance/landing/widgets/widgets/lineChartListWidget.tsx
index c2553399e0790e..3c333a90fbc3c0 100644
--- a/static/app/views/performance/landing/widgets/widgets/lineChartListWidget.tsx
+++ b/static/app/views/performance/landing/widgets/widgets/lineChartListWidget.tsx
@@ -27,8 +27,11 @@ import withApi from 'sentry/utils/withApi';
import {normalizeUrl} from 'sentry/utils/withDomainRequired';
import {DEFAULT_RESOURCE_TYPES} from 'sentry/views/performance/browser/resources/resourceView';
import {getResourcesEventViewQuery} from 'sentry/views/performance/browser/resources/utils/useResourcesQuery';
+import {BASE_URL as RESOURCES_BASE_URL} from 'sentry/views/performance/browser/webVitals/settings';
import {BASE_FILTERS, CACHE_BASE_URL} from 'sentry/views/performance/cache/settings';
import DurationChart from 'sentry/views/performance/charts/chart';
+import {BASE_URL as DATABASE_BASE_URL} from 'sentry/views/performance/database/settings';
+import {BASE_URL as HTTP_BASE_URL} from 'sentry/views/performance/http/settings';
import {DomainCell} from 'sentry/views/performance/http/tables/domainCell';
import {transactionSummaryRouteWithQuery} from 'sentry/views/performance/transactionSummary/utils';
import {
@@ -604,7 +607,9 @@ export function LineChartListWidget(props: PerformanceWidgetProps) {
);
case PerformanceWidgetSetting.MOST_TIME_CONSUMING_DOMAINS:
return (
- <RoutingContextProvider value={{baseURL: '/performance/http'}}>
+ <RoutingContextProvider
+ value={{baseURL: `/performance/${HTTP_BASE_URL}`}}
+ >
<Fragment>
<StyledTextOverflow>
<DomainCell
@@ -650,8 +655,8 @@ export function LineChartListWidget(props: PerformanceWidgetProps) {
const moduleName = isQueriesWidget ? ModuleName.DB : ModuleName.RESOURCE;
const timeSpentOp = isQueriesWidget ? 'op' : undefined;
const routingContextBaseURL = isQueriesWidget
- ? '/performance/database'
- : '/performance/browser/resources';
+ ? `/performance/${DATABASE_BASE_URL}`
+ : `/performance/${RESOURCES_BASE_URL}`;
return (
<RoutingContextProvider value={{baseURL: routingContextBaseURL}}>
<Fragment>
diff --git a/static/app/views/performance/mobile/appStarts/index.tsx b/static/app/views/performance/mobile/appStarts/index.tsx
index e104e47f41c6a7..873f9156d39ab6 100644
--- a/static/app/views/performance/mobile/appStarts/index.tsx
+++ b/static/app/views/performance/mobile/appStarts/index.tsx
@@ -1,5 +1,6 @@
import AppStartup from 'sentry/views/performance/mobile/appStarts/screens';
import {StartTypeSelector} from 'sentry/views/performance/mobile/appStarts/screenSummary/startTypeSelector';
+import {BASE_URL} from 'sentry/views/performance/mobile/appStarts/settings';
import ScreensTemplate from 'sentry/views/performance/mobile/components/screensTemplate';
import {ModulePageProviders} from 'sentry/views/performance/modulePageProviders';
import {ROUTE_NAMES} from 'sentry/views/starfish/utils/routeNames';
@@ -18,7 +19,7 @@ function PageWithProviders() {
return (
<ModulePageProviders
title={ROUTE_NAMES['app-startup']}
- baseURL="/performance/mobile/app-startup"
+ baseURL={`/performance/${BASE_URL}`}
features="spans-first-ui"
>
<InitializationModule />
diff --git a/static/app/views/performance/mobile/appStarts/screenSummary/index.tsx b/static/app/views/performance/mobile/appStarts/screenSummary/index.tsx
index 6c70add6115156..130386aa438719 100644
--- a/static/app/views/performance/mobile/appStarts/screenSummary/index.tsx
+++ b/static/app/views/performance/mobile/appStarts/screenSummary/index.tsx
@@ -24,6 +24,7 @@ import {
COLD_START_TYPE,
StartTypeSelector,
} from 'sentry/views/performance/mobile/appStarts/screenSummary/startTypeSelector';
+import {BASE_URL} from 'sentry/views/performance/mobile/appStarts/settings';
import {MetricsRibbon} from 'sentry/views/performance/mobile/screenload/screenLoadSpans/metricsRibbon';
import {ScreenLoadSpanSamples} from 'sentry/views/performance/mobile/screenload/screenLoadSpans/samples';
import {ModulePageProviders} from 'sentry/views/performance/modulePageProviders';
@@ -224,7 +225,7 @@ function PageWithProviders() {
return (
<ModulePageProviders
title={[transaction, ROUTE_NAMES['app-startup']].join(' — ')}
- baseURL="/performance/mobile/app-startup/spans"
+ baseURL={`/performance/${BASE_URL}`}
features="spans-first-ui"
>
<ScreenSummary />
diff --git a/static/app/views/performance/mobile/appStarts/settings.ts b/static/app/views/performance/mobile/appStarts/settings.ts
new file mode 100644
index 00000000000000..638f5cf942fdf7
--- /dev/null
+++ b/static/app/views/performance/mobile/appStarts/settings.ts
@@ -0,0 +1,4 @@
+import {t} from 'sentry/locale';
+
+export const MODULE_TITLE = t('App Starts');
+export const BASE_URL = 'mobile/app-startup';
diff --git a/static/app/views/performance/mobile/screenload/index.tsx b/static/app/views/performance/mobile/screenload/index.tsx
index 71840409c8bdee..1d621446ccba26 100644
--- a/static/app/views/performance/mobile/screenload/index.tsx
+++ b/static/app/views/performance/mobile/screenload/index.tsx
@@ -21,6 +21,7 @@ import {useOnboardingProject} from 'sentry/views/performance/browser/webVitals/u
import {ScreensView, YAxis} from 'sentry/views/performance/mobile/screenload/screens';
import {PlatformSelector} from 'sentry/views/performance/mobile/screenload/screens/platformSelector';
import {isCrossPlatform} from 'sentry/views/performance/mobile/screenload/screens/utils';
+import {BASE_URL} from 'sentry/views/performance/mobile/screenload/settings';
import {ModulePageProviders} from 'sentry/views/performance/modulePageProviders';
import Onboarding from 'sentry/views/performance/onboarding';
import {ReleaseComparisonSelector} from 'sentry/views/starfish/components/releaseSelector';
@@ -104,7 +105,7 @@ function PageWithProviders() {
return (
<ModulePageProviders
title={t('Screen Loads')}
- baseURL="/performance/mobile/screens"
+ baseURL={`/performance/${BASE_URL}`}
features="spans-first-ui"
>
<PageloadModule />
diff --git a/static/app/views/performance/mobile/screenload/screenLoadSpans/index.tsx b/static/app/views/performance/mobile/screenload/screenLoadSpans/index.tsx
index 27ee23ace484df..80c7f4c0ff1eda 100644
--- a/static/app/views/performance/mobile/screenload/screenLoadSpans/index.tsx
+++ b/static/app/views/performance/mobile/screenload/screenLoadSpans/index.tsx
@@ -35,6 +35,7 @@ import {
} from 'sentry/views/performance/mobile/screenload/screens/constants';
import {PlatformSelector} from 'sentry/views/performance/mobile/screenload/screens/platformSelector';
import {isCrossPlatform} from 'sentry/views/performance/mobile/screenload/screens/utils';
+import {BASE_URL} from 'sentry/views/performance/mobile/screenload/settings';
import {ModulePageProviders} from 'sentry/views/performance/modulePageProviders';
import {
PRIMARY_RELEASE_ALIAS,
@@ -240,7 +241,7 @@ function PageWithProviders() {
return (
<ModulePageProviders
title={[transaction, t('Screen Loads')].join(' — ')}
- baseURL="/performance/mobile/screens"
+ baseURL={`/performance/${BASE_URL}`}
features="spans-first-ui"
>
<ScreenLoadSpans />
diff --git a/static/app/views/performance/mobile/screenload/settings.ts b/static/app/views/performance/mobile/screenload/settings.ts
new file mode 100644
index 00000000000000..cbb5ccbaf40b5e
--- /dev/null
+++ b/static/app/views/performance/mobile/screenload/settings.ts
@@ -0,0 +1,4 @@
+import {t} from 'sentry/locale';
+
+export const MODULE_TITLE = t('Screen Loads');
+export const BASE_URL = 'mobile/screens';
diff --git a/static/app/views/performance/mobile/ui/index.tsx b/static/app/views/performance/mobile/ui/index.tsx
index e590860d955dbc..a84a7a5bed8b61 100644
--- a/static/app/views/performance/mobile/ui/index.tsx
+++ b/static/app/views/performance/mobile/ui/index.tsx
@@ -1,5 +1,6 @@
import ScreensTemplate from 'sentry/views/performance/mobile/components/screensTemplate';
import {UIScreens} from 'sentry/views/performance/mobile/ui/screens';
+import {BASE_URL} from 'sentry/views/performance/mobile/ui/settings';
import {ModulePageProviders} from 'sentry/views/performance/modulePageProviders';
import {ROUTE_NAMES} from 'sentry/views/starfish/utils/routeNames';
@@ -11,7 +12,7 @@ function PageWithProviders() {
return (
<ModulePageProviders
title={ROUTE_NAMES.mobileUI}
- baseURL="/performance/mobile/ui"
+ baseURL={`/performance/${BASE_URL}`}
features={['spans-first-ui', 'starfish-mobile-ui-module']}
>
<ResponsivenessModule />
diff --git a/static/app/views/performance/mobile/ui/screenSummary/index.tsx b/static/app/views/performance/mobile/ui/screenSummary/index.tsx
index d2ba9475aa9561..7b3e3cc7246e94 100644
--- a/static/app/views/performance/mobile/ui/screenSummary/index.tsx
+++ b/static/app/views/performance/mobile/ui/screenSummary/index.tsx
@@ -16,6 +16,7 @@ import {normalizeUrl} from 'sentry/utils/withDomainRequired';
import {SamplesTables} from 'sentry/views/performance/mobile/components/samplesTables';
import {ScreenLoadSpanSamples} from 'sentry/views/performance/mobile/screenload/screenLoadSpans/samples';
import {SpanOperationTable} from 'sentry/views/performance/mobile/ui/screenSummary/spanOperationTable';
+import {BASE_URL} from 'sentry/views/performance/mobile/ui/settings';
import {ModulePageProviders} from 'sentry/views/performance/modulePageProviders';
import {ReleaseComparisonSelector} from 'sentry/views/starfish/components/releaseSelector';
import {SpanMetricsField} from 'sentry/views/starfish/types';
@@ -138,7 +139,7 @@ function PageWithProviders() {
return (
<ModulePageProviders
title={[transaction, t('Screen Loads')].join(' — ')}
- baseURL="/performance/mobile/ui/spans"
+ baseURL={`/performance/${BASE_URL}`}
features={['spans-first-ui', 'starfish-mobile-ui-module']}
>
<ScreenSummary />
diff --git a/static/app/views/performance/mobile/ui/settings.ts b/static/app/views/performance/mobile/ui/settings.ts
new file mode 100644
index 00000000000000..68331178dc46b3
--- /dev/null
+++ b/static/app/views/performance/mobile/ui/settings.ts
@@ -0,0 +1,4 @@
+import {t} from 'sentry/locale';
+
+export const MODULE_TITLE = t('Mobile UI');
+export const BASE_URL = 'mobile/ui';
diff --git a/static/app/views/performance/queues/destinationSummary/destinationSummaryPage.tsx b/static/app/views/performance/queues/destinationSummary/destinationSummaryPage.tsx
index 6c26d9d5cf7649..f009c0928675a7 100644
--- a/static/app/views/performance/queues/destinationSummary/destinationSummaryPage.tsx
+++ b/static/app/views/performance/queues/destinationSummary/destinationSummaryPage.tsx
@@ -28,6 +28,7 @@ import {TransactionsTable} from 'sentry/views/performance/queues/destinationSumm
import {MessageSamplesPanel} from 'sentry/views/performance/queues/messageSamplesPanel';
import {useQueuesMetricsQuery} from 'sentry/views/performance/queues/queries/useQueuesMetricsQuery';
import {
+ BASE_URL,
DESTINATION_TITLE,
MODULE_TITLE,
RELEASE_LEVEL,
@@ -164,7 +165,7 @@ function PageWithProviders() {
return (
<ModulePageProviders
title={[t('Performance'), MODULE_TITLE].join(' — ')}
- baseURL="/performance/queues"
+ baseURL={`/performance/${BASE_URL}`}
features="performance-queues-view"
>
<DestinationSummaryPage />
diff --git a/static/app/views/performance/queues/queuesLandingPage.tsx b/static/app/views/performance/queues/queuesLandingPage.tsx
index 90cbf3028c5631..64bbfeabe9fca8 100644
--- a/static/app/views/performance/queues/queuesLandingPage.tsx
+++ b/static/app/views/performance/queues/queuesLandingPage.tsx
@@ -27,7 +27,11 @@ import Onboarding from 'sentry/views/performance/onboarding';
import {LatencyChart} from 'sentry/views/performance/queues/charts/latencyChart';
import {ThroughputChart} from 'sentry/views/performance/queues/charts/throughputChart';
import {isAValidSort, QueuesTable} from 'sentry/views/performance/queues/queuesTable';
-import {MODULE_TITLE, RELEASE_LEVEL} from 'sentry/views/performance/queues/settings';
+import {
+ BASE_URL,
+ MODULE_TITLE,
+ RELEASE_LEVEL,
+} from 'sentry/views/performance/queues/settings';
import {QueryParameterNames} from 'sentry/views/starfish/views/queryParameters';
const DEFAULT_SORT = {
@@ -147,7 +151,7 @@ function PageWithProviders() {
return (
<ModulePageProviders
title={[t('Performance'), MODULE_TITLE].join(' — ')}
- baseURL="/performance/queues"
+ baseURL={`/performance/${BASE_URL}`}
features="performance-queues-view"
>
<QueuesLandingPage />
diff --git a/static/app/views/performance/queues/settings.ts b/static/app/views/performance/queues/settings.ts
index 13f7e2b0c3a6e0..bc42f963775c93 100644
--- a/static/app/views/performance/queues/settings.ts
+++ b/static/app/views/performance/queues/settings.ts
@@ -2,6 +2,7 @@ import type {BadgeType} from 'sentry/components/badge/featureBadge';
import {t} from 'sentry/locale';
export const MODULE_TITLE = t('Queues');
+export const BASE_URL = 'queues';
export const DESTINATION_TITLE = t('Destination Summary');
diff --git a/static/app/views/performance/settings.ts b/static/app/views/performance/settings.ts
new file mode 100644
index 00000000000000..0d32d796980ca2
--- /dev/null
+++ b/static/app/views/performance/settings.ts
@@ -0,0 +1 @@
+export const INSIGHTS_BASE_URL = '/performance';
|
7fad89315adb4f9ef16b9051b3b3f8205c3ff5fe
|
2023-02-07 01:49:32
|
Kev
|
fix(perf): Add link to url in transaction details (#44177)
| false
|
Add link to url in transaction details (#44177)
|
fix
|
diff --git a/static/app/components/tagsTableRow.tsx b/static/app/components/tagsTableRow.tsx
index c57115baf5d460..dbdce1b007877c 100644
--- a/static/app/components/tagsTableRow.tsx
+++ b/static/app/components/tagsTableRow.tsx
@@ -3,11 +3,14 @@ import {LocationDescriptor} from 'history';
import {AnnotatedText} from 'sentry/components/events/meta/annotatedText';
import {KeyValueTableRow} from 'sentry/components/keyValueTable';
+import ExternalLink from 'sentry/components/links/externalLink';
import Link from 'sentry/components/links/link';
import {Tooltip} from 'sentry/components/tooltip';
import Version from 'sentry/components/version';
+import {IconOpen} from 'sentry/icons';
import {t} from 'sentry/locale';
import {EventTag} from 'sentry/types/event';
+import {isUrl} from 'sentry/utils';
interface Props {
generateUrl: (tag: EventTag) => LocationDescriptor;
@@ -50,6 +53,18 @@ function TagsTableRow({tag, query, generateUrl, meta}: Props) {
<StyledTooltip title={t('This tag is in the current filter conditions')}>
<ValueContainer>{renderTagValue()}</ValueContainer>
</StyledTooltip>
+ ) : tag.key === 'url' ? (
+ <ValueWithExtraContainer>
+ <StyledTooltip title={renderTagValue()} showOnlyOnOverflow>
+ <Link to={target || ''}>{renderTagValue()}</Link>
+ </StyledTooltip>
+
+ {isUrl(tag.value) && (
+ <ExternalLink href={tag.value} className="external-icon">
+ <IconOpen size="xs" />
+ </ExternalLink>
+ )}
+ </ValueWithExtraContainer>
) : (
<StyledTooltip title={renderTagValue()} showOnlyOnOverflow>
<Link to={target || ''}>{renderTagValue()}</Link>
@@ -72,3 +87,8 @@ const ValueContainer = styled('span')`
text-overflow: ellipsis;
line-height: normal;
`;
+
+const ValueWithExtraContainer = styled('span')`
+ display: flex;
+ align-items: center;
+`;
|
7d271b0e6dc5b48b891e85793ea0769ca2a34a69
|
2022-10-25 15:36:24
|
Ahmed Etefy
|
fix(ds): pexpire expects milliseconds not seconds (#40503)
| false
|
pexpire expects milliseconds not seconds (#40503)
|
fix
|
diff --git a/src/sentry/dynamic_sampling/latest_release_booster.py b/src/sentry/dynamic_sampling/latest_release_booster.py
index 1ddace46264c38..ae55f61a387a38 100644
--- a/src/sentry/dynamic_sampling/latest_release_booster.py
+++ b/src/sentry/dynamic_sampling/latest_release_booster.py
@@ -6,7 +6,7 @@
from sentry.utils import redis
BOOSTED_RELEASE_TIMEOUT = 60 * 60
-ONE_DAY_TIMEOUT = 60 * 60 * 24
+ONE_DAY_TIMEOUT_MS = 60 * 60 * 24 * 1000
def get_redis_client_for_ds():
@@ -39,7 +39,7 @@ def observe_release(project_id, release_id):
# TODO(ahmed): Modify these two statements into one once we upgrade to a higher redis-py version as in newer
# versions these two operations can be done in a single call.
release_observed = redis_client.getset(name=cache_key, value=1)
- redis_client.pexpire(cache_key, ONE_DAY_TIMEOUT)
+ redis_client.pexpire(cache_key, ONE_DAY_TIMEOUT_MS)
return release_observed == "1"
@@ -82,4 +82,4 @@ def add_boosted_release(project_id, release_id):
release_id,
datetime.utcnow().replace(tzinfo=UTC).timestamp(),
)
- redis_client.pexpire(cache_key, ONE_DAY_TIMEOUT)
+ redis_client.pexpire(cache_key, BOOSTED_RELEASE_TIMEOUT * 1000)
|
c796a59aefc21fd5c38f8f0910a64eaf399b93fa
|
2023-12-08 23:14:13
|
Ryan Albrecht
|
feat(feedback): Urls to feedbacks should include the project that the feedback is part of (#61169)
| false
|
Urls to feedbacks should include the project that the feedback is part of (#61169)
|
feat
|
diff --git a/src/sentry/models/group.py b/src/sentry/models/group.py
index 61b308abefb651..a3780ae347e443 100644
--- a/src/sentry/models/group.py
+++ b/src/sentry/models/group.py
@@ -602,9 +602,11 @@ def get_absolute_url(
if self.issue_category == GroupCategory.FEEDBACK:
path = f"/organizations/{organization.slug}/feedback/"
slug = {"feedbackSlug": f"{self.project.slug}:{self.id}"}
+ project = {"project": self.project.id}
params = {
**(params or {}),
**slug,
+ **project,
}
query = urlencode(params)
return organization.absolute_url(path, query=query)
diff --git a/tests/sentry/models/test_group.py b/tests/sentry/models/test_group.py
index 5b16e274ff7543..8d04c90b1e130b 100644
--- a/tests/sentry/models/test_group.py
+++ b/tests/sentry/models/test_group.py
@@ -242,9 +242,7 @@ def test_get_absolute_url_feedback(self):
project = self.create_project(organization=org)
group_id = 23
params = None
- expected = (
- f"http://testserver/organizations/org1/feedback/?feedbackSlug={project.slug}%3A23"
- )
+ expected = f"http://testserver/organizations/org1/feedback/?feedbackSlug={project.slug}%3A23&project={project.id}"
group = self.create_group(id=group_id, project=project, type=FeedbackGroup.type_id)
actual = group.get_absolute_url(params)
|
6c06912968c8bb5e78b9f3761364b0154eb2898d
|
2022-03-17 03:21:21
|
Stephen Cefali
|
feat(vercel): allow a single Sentry project to map to multiple Vercel projects (#32639)
| false
|
allow a single Sentry project to map to multiple Vercel projects (#32639)
|
feat
|
diff --git a/static/app/components/forms/projectMapperField.tsx b/static/app/components/forms/projectMapperField.tsx
index 1ba4571315ea80..f42680a4714111 100644
--- a/static/app/components/forms/projectMapperField.tsx
+++ b/static/app/components/forms/projectMapperField.tsx
@@ -83,13 +83,10 @@ export class RenderField extends Component<RenderProps, State> {
mappedDropdownItems.map(item => [item.value, item])
);
- // build sets of values used so we don't let the user select them twice
- const projectIdsUsed = new Set(existingValues.map(tuple => tuple[0]));
+ // prevent a single mapped item from being associated with multiple Sentry projects
const mappedValuesUsed = new Set(existingValues.map(tuple => tuple[1]));
- const projectOptions = sentryProjects
- .filter(project => !projectIdsUsed.has(project.id))
- .map(({slug, id}) => ({label: slug, value: id}));
+ const projectOptions = sentryProjects.map(({slug, id}) => ({label: slug, value: id}));
const mappedItemsToShow = mappedDropdownItems.filter(
item => !mappedValuesUsed.has(item.value)
@@ -129,19 +126,6 @@ export class RenderField extends Component<RenderProps, State> {
const mappedItem = mappedItemsByValue[mappedValue];
return (
<Item key={index}>
- <MappedProjectWrapper>
- {project ? (
- <IdBadge
- project={project}
- avatarSize={20}
- displayName={project.slug}
- avatarProps={{consistentWidth: true}}
- />
- ) : (
- t('Deleted')
- )}
- <IconArrow size="xs" direction="right" />
- </MappedProjectWrapper>
<MappedItemValue>
{mappedItem ? (
<Fragment>
@@ -154,7 +138,20 @@ export class RenderField extends Component<RenderProps, State> {
) : (
t('Deleted')
)}
+ <IconArrow size="xs" direction="right" />
</MappedItemValue>
+ <MappedProjectWrapper>
+ {project ? (
+ <IdBadge
+ project={project}
+ avatarSize={20}
+ displayName={project.slug}
+ avatarProps={{consistentWidth: true}}
+ />
+ ) : (
+ t('Deleted')
+ )}
+ </MappedProjectWrapper>
<DeleteButtonWrapper>
<Button
onClick={() => handleDelete(index)}
@@ -235,17 +232,6 @@ export class RenderField extends Component<RenderProps, State> {
<Fragment>
{existingValues.map(renderItem)}
<Item>
- <SelectControl
- placeholder={t('Sentry project\u2026')}
- name="project"
- options={projectOptions}
- components={{
- Option: customOptionProject,
- ValueContainer: customValueContainer,
- }}
- onChange={handleSelectProject}
- value={selectedSentryProjectId}
- />
<SelectControl
placeholder={mappedValuePlaceholder}
name="mappedDropdown"
@@ -257,6 +243,17 @@ export class RenderField extends Component<RenderProps, State> {
onChange={handleSelectMappedValue}
value={selectedMappedValue}
/>
+ <SelectControl
+ placeholder={t('Sentry project\u2026')}
+ name="project"
+ options={projectOptions}
+ components={{
+ Option: customOptionProject,
+ ValueContainer: customValueContainer,
+ }}
+ onChange={handleSelectProject}
+ value={selectedSentryProjectId}
+ />
<AddProjectWrapper>
<Button
type="button"
@@ -332,7 +329,7 @@ const Item = styled('div')`
grid-column-gap: ${space(1)};
align-items: center;
grid-template-columns: 2.5fr 2.5fr max-content 30px;
- grid-template-areas: 'sentry-project mapped-value manage-project field-control';
+ grid-template-areas: 'mapped-value sentry-project manage-project field-control';
`;
const MappedItemValue = styled('div')`
diff --git a/tests/js/spec/components/deprecatedforms/projectMapperField.spec.jsx b/tests/js/spec/components/deprecatedforms/projectMapperField.spec.jsx
index 8ea6a4441da77d..46e3975b61e1ab 100644
--- a/tests/js/spec/components/deprecatedforms/projectMapperField.spec.jsx
+++ b/tests/js/spec/components/deprecatedforms/projectMapperField.spec.jsx
@@ -1,5 +1,5 @@
import {mountWithTheme} from 'sentry-test/enzyme';
-import {selectByValue} from 'sentry-test/select-new';
+import {findOption, openMenu, selectByValue} from 'sentry-test/select-new';
import {RenderField} from 'sentry/components/forms/projectMapperField';
@@ -72,5 +72,22 @@ describe('ProjectMapperField', () => {
expect(onChange).toHaveBeenCalledWith([['24', '1']], []);
});
- it('handles deleted items without error', () => {});
+ it('allows a single Sentry project to map to multiple items but not the value', () => {
+ existingValues = [['24', '1']];
+ wrapper = mountWithTheme(<RenderField {...props} value={existingValues} />);
+ // can find the same project again
+ openMenu(wrapper, {control: true, name: 'project'});
+ expect(
+ findOption(wrapper, {value: '24'}, {control: true, name: 'project'})
+ ).toHaveLength(1);
+ // but not the value
+ openMenu(wrapper, {control: true, name: 'mappedDropdown'});
+ expect(
+ findOption(wrapper, {value: '1'}, {control: true, name: 'mappedDropdown'})
+ ).toHaveLength(0);
+ // validate we can still find 2
+ expect(
+ findOption(wrapper, {value: '2'}, {control: true, name: 'mappedDropdown'})
+ ).toHaveLength(1);
+ });
});
|
eeda04cd1955b746c754311d41672fe4c4dc5445
|
2022-05-17 20:29:32
|
David Wang
|
feat(page-filters): Remove feature flag from issues page (#34149)
| false
|
Remove feature flag from issues page (#34149)
|
feat
|
diff --git a/static/app/components/datePageFilter.tsx b/static/app/components/datePageFilter.tsx
index 6f99421ebfb6cf..48dd3943a51f69 100644
--- a/static/app/components/datePageFilter.tsx
+++ b/static/app/components/datePageFilter.tsx
@@ -58,6 +58,7 @@ function DatePageFilter({router, resetParamsOnChange, ...props}: Props) {
hideBottomBorder={false}
isOpen={isOpen}
highlighted={desyncedFilters.has('datetime')}
+ data-test-id="global-header-timerange-selector"
{...getActorProps()}
>
<DropdownTitle>
diff --git a/static/app/components/environmentPageFilter.tsx b/static/app/components/environmentPageFilter.tsx
index 7877773ffd22a6..9863e149fb0211 100644
--- a/static/app/components/environmentPageFilter.tsx
+++ b/static/app/components/environmentPageFilter.tsx
@@ -66,6 +66,7 @@ function EnvironmentPageFilter({
hideBottomBorder={false}
isOpen={isOpen}
highlighted={desyncedFilters.has('environments')}
+ data-test-id="global-header-environment-selector"
>
<DropdownTitle>
<PageFilterPinIndicator filter="environments">
@@ -83,7 +84,11 @@ function EnvironmentPageFilter({
};
const customLoadingIndicator = (
- <PageFilterDropdownButton showChevron={false} disabled>
+ <PageFilterDropdownButton
+ showChevron={false}
+ disabled
+ data-test-id="global-header-environment-selector"
+ >
<DropdownTitle>
<IconWindow />
<TitleContainer>{t('Loading\u2026')}</TitleContainer>
diff --git a/static/app/components/organizations/pageFilters/utils.tsx b/static/app/components/organizations/pageFilters/utils.tsx
index 9581fca1a3acf1..7e4e5190cbfa40 100644
--- a/static/app/components/organizations/pageFilters/utils.tsx
+++ b/static/app/components/organizations/pageFilters/utils.tsx
@@ -94,6 +94,7 @@ export function doesPathHaveNewFilters(pathname: string, organization: Organizat
'user-feedback',
'alerts',
'monitors',
+ 'issues',
'projects',
'dashboards',
'releases',
diff --git a/static/app/components/projectPageFilter.tsx b/static/app/components/projectPageFilter.tsx
index 8364d9ad8e6928..286ca7968e0605 100644
--- a/static/app/components/projectPageFilter.tsx
+++ b/static/app/components/projectPageFilter.tsx
@@ -164,6 +164,7 @@ function ProjectPageFilter({
hideBottomBorder={false}
isOpen={isOpen}
highlighted={desyncedFilters.has('projects')}
+ data-test-id="global-header-project-selector"
>
<DropdownTitle>
<PageFilterPinIndicator filter="projects">{icon}</PageFilterPinIndicator>
@@ -178,7 +179,11 @@ function ProjectPageFilter({
};
const customLoadingIndicator = (
- <PageFilterDropdownButton showChevron={false} disabled>
+ <PageFilterDropdownButton
+ showChevron={false}
+ disabled
+ data-test-id="global-header-project-selector-loading"
+ >
<DropdownTitle>
<IconProject />
<TitleContainer>{t('Loading\u2026')}</TitleContainer>
diff --git a/static/app/views/issueList/container.tsx b/static/app/views/issueList/container.tsx
index 1e7da075b50899..3bdeeb40f00368 100644
--- a/static/app/views/issueList/container.tsx
+++ b/static/app/views/issueList/container.tsx
@@ -15,9 +15,7 @@ function IssueListContainer({children}: Props) {
return (
<SentryDocumentTitle title={t('Issues')} orgSlug={organization.slug}>
- <PageFiltersContainer
- hideGlobalHeader={organization.features.includes('selection-filters-v2')}
- >
+ <PageFiltersContainer hideGlobalHeader>
<NoProjectMessage organization={organization}>{children}</NoProjectMessage>
</PageFiltersContainer>
</SentryDocumentTitle>
diff --git a/tests/acceptance/page_objects/global_selection.py b/tests/acceptance/page_objects/global_selection.py
index c92c5f8bd6417d..735bfc983b71f2 100644
--- a/tests/acceptance/page_objects/global_selection.py
+++ b/tests/acceptance/page_objects/global_selection.py
@@ -24,6 +24,11 @@ def select_project_by_slug(self, slug):
self.browser.wait_until(xpath=project_item_selector)
self.browser.click(xpath=project_item_selector)
+ def lock_project_filter(self):
+ self.open_project_selector()
+ self.browser.wait_until('[aria-label="Lock filter"]')
+ self.browser.click('[aria-label="Lock filter"]')
+
def open_environment_selector(self):
self.browser.click('[data-test-id="global-header-environment-selector"]')
diff --git a/tests/acceptance/test_organization_global_selection_header.py b/tests/acceptance/test_organization_global_selection_header.py
index 49757a2728734f..f2342af9e4d0e3 100644
--- a/tests/acceptance/test_organization_global_selection_header.py
+++ b/tests/acceptance/test_organization_global_selection_header.py
@@ -165,9 +165,7 @@ def test_global_selection_header_updates_environment_with_browser_navigation_but
self.issues_list.visit_issue_list(self.org.slug)
self.issues_list.wait_until_loaded()
assert "environment=" not in self.browser.current_url
- assert (
- self.issue_details.global_selection.get_selected_environment() == "All Environments"
- )
+ assert self.issue_details.global_selection.get_selected_environment() == "All Env"
self.browser.click('[data-test-id="global-header-environment-selector"]')
self.browser.click('[data-test-id="environment-prod"]')
@@ -175,17 +173,18 @@ def test_global_selection_header_updates_environment_with_browser_navigation_but
assert "environment=prod" in self.browser.current_url
assert self.issue_details.global_selection.get_selected_environment() == "prod"
- self.browser.click('[data-test-id="global-header-environment-selector"] > svg')
+ # clear environment prod
+ self.browser.click('[data-test-id="global-header-environment-selector"]')
+ self.browser.click('[data-test-id="environment-prod"] [role="checkbox"]')
+ self.browser.click('[data-test-id="global-header-environment-selector"]')
self.issues_list.wait_until_loaded()
assert "environment=" not in self.browser.current_url
- assert (
- self.issue_details.global_selection.get_selected_environment() == "All Environments"
- )
+ assert self.issue_details.global_selection.get_selected_environment() == "All Env"
"""
navigate back through history to the beginning
- 1) environment=All Environments -> environment=prod
- 2) environment=prod -> environment=All Environments
+ 1) environment=All Env -> environment=prod
+ 2) environment=prod -> environment=All Env
"""
self.browser.back()
self.issues_list.wait_until_loaded()
@@ -195,14 +194,12 @@ def test_global_selection_header_updates_environment_with_browser_navigation_but
self.browser.back()
self.issues_list.wait_until_loaded()
assert "environment=" not in self.browser.current_url
- assert (
- self.issue_details.global_selection.get_selected_environment() == "All Environments"
- )
+ assert self.issue_details.global_selection.get_selected_environment() == "All Env"
"""
navigate forward through history to the end
- 1) environment=All Environments -> environment=prod
- 2) environment=prod -> environment=All Environments
+ 1) environment=All Env -> environment=prod
+ 2) environment=prod -> environment=All Env
"""
self.browser.forward()
self.issues_list.wait_until_loaded()
@@ -212,9 +209,7 @@ def test_global_selection_header_updates_environment_with_browser_navigation_but
self.browser.forward()
self.issues_list.wait_until_loaded()
assert "environment=" not in self.browser.current_url
- assert (
- self.issue_details.global_selection.get_selected_environment() == "All Environments"
- )
+ assert self.issue_details.global_selection.get_selected_environment() == "All Env"
def test_global_selection_header_loads_with_correct_project_with_multi_project(self):
"""
@@ -261,6 +256,9 @@ def test_global_selection_header_loads_with_correct_project_with_multi_project(s
# This doesn't work because we treat as dynamic data in CI
# assert self.issues_list.global_selection.get_selected_date() == "Last 24 hours"
+ # lock the filter and then test reloading the page to test persistence
+ self.issues_list.global_selection.lock_project_filter()
+
# reloading page with no project id in URL after previously
# selecting an explicit project should load previously selected project
# from local storage
|
7450b5c17c91f1dc32c9ea9e4591ac4b5891388d
|
2022-09-01 02:22:26
|
Evan Purkhiser
|
ref(js): Fix dependency wanrings in persistedStore (#38353)
| false
|
Fix dependency wanrings in persistedStore (#38353)
|
ref
|
diff --git a/static/app/stores/persistedStore.tsx b/static/app/stores/persistedStore.tsx
index 0b4d9b896dc168..955b82e224117a 100644
--- a/static/app/stores/persistedStore.tsx
+++ b/static/app/stores/persistedStore.tsx
@@ -83,6 +83,7 @@ export function PersistedStoreProvider(props: {children: React.ReactNode}) {
}
type UsePersistedCategory<T> = [T | null, (nextState: T | null) => void];
+
export function usePersistedStoreCategory<C extends keyof PersistedStore>(
category: C
): UsePersistedCategory<PersistedStore[C]> {
@@ -109,12 +110,14 @@ export function usePersistedStoreCategory<C extends keyof PersistedStore>(
data: val,
});
},
- [category, organization, api]
+ [setState, category, organization, api]
);
+ const result = state[category];
+
const stableState: UsePersistedCategory<PersistedStore[C]> = useMemo(() => {
- return [state[category] ?? null, setCategoryState];
- }, [state[category], setCategoryState]);
+ return [result ?? null, setCategoryState];
+ }, [result, setCategoryState]);
return stableState;
}
|
016abf1378daebf6a10b477248f1e6cb3289f363
|
2022-12-22 03:06:15
|
David Wang
|
feat(crons): Allow click to copy monitor id (#42526)
| false
|
Allow click to copy monitor id (#42526)
|
feat
|
diff --git a/static/app/views/monitors/monitorHeader.tsx b/static/app/views/monitors/monitorHeader.tsx
index 588df6a5e9e97f..6aa8a59ab47445 100644
--- a/static/app/views/monitors/monitorHeader.tsx
+++ b/static/app/views/monitors/monitorHeader.tsx
@@ -2,9 +2,11 @@ import styled from '@emotion/styled';
import Breadcrumbs from 'sentry/components/breadcrumbs';
import {SectionHeading} from 'sentry/components/charts/styles';
+import Clipboard from 'sentry/components/clipboard';
import IdBadge from 'sentry/components/idBadge';
import * as Layout from 'sentry/components/layouts/thirds';
import TimeSince from 'sentry/components/timeSince';
+import {IconCopy} from 'sentry/icons';
import {t} from 'sentry/locale';
import space from 'sentry/styles/space';
@@ -48,7 +50,11 @@ const MonitorHeader = ({monitor, orgId, onUpdate}: Props) => {
{monitor.name}
</MonitorName>
</Layout.Title>
- <MonitorId>{monitor.id}</MonitorId>
+ <Clipboard value={monitor.id}>
+ <MonitorId>
+ {monitor.id} <IconCopy size="xs" />
+ </MonitorId>
+ </Clipboard>
</Layout.HeaderContent>
<Layout.HeaderActions>
<MonitorHeaderActions orgId={orgId} monitor={monitor} onUpdate={onUpdate} />
@@ -78,6 +84,7 @@ const MonitorName = styled('div')`
const MonitorId = styled('div')`
margin-top: ${space(1)};
color: ${p => p.theme.subText};
+ cursor: pointer;
`;
const MonitorStats = styled('div')`
|
63045db9fde24cdf9d60b30356959d67bf4c2aad
|
2020-11-07 04:49:38
|
Tony
|
feat(vitals): Remove beta badge and EA alert (#21848)
| false
|
Remove beta badge and EA alert (#21848)
|
feat
|
diff --git a/src/sentry/static/sentry/app/views/performance/transactionSummary/header.tsx b/src/sentry/static/sentry/app/views/performance/transactionSummary/header.tsx
index 1e3d3b35be55d7..ad56ac9cb3185a 100644
--- a/src/sentry/static/sentry/app/views/performance/transactionSummary/header.tsx
+++ b/src/sentry/static/sentry/app/views/performance/transactionSummary/header.tsx
@@ -4,16 +4,12 @@ import styled from '@emotion/styled';
import {Organization, Project} from 'app/types';
import EventView from 'app/utils/discover/eventView';
-import Alert from 'app/components/alert';
import Feature from 'app/components/acl/feature';
-import FeatureBadge from 'app/components/featureBadge';
import CreateAlertButton from 'app/components/createAlertButton';
import * as Layout from 'app/components/layouts/thirds';
-import ExternalLink from 'app/components/links/externalLink';
import ButtonBar from 'app/components/buttonBar';
import ListLink from 'app/components/links/listLink';
import NavTabs from 'app/components/navTabs';
-import {IconInfo} from 'app/icons';
import {t} from 'app/locale';
import {trackAnalyticsEvent} from 'app/utils/analytics';
import Breadcrumb from 'app/views/performance/breadcrumb';
@@ -148,16 +144,6 @@ class TransactionHeader extends React.Component<Props> {
});
return (
<React.Fragment>
- {currentTab === Tab.RealUserMonitoring && (
- <StyledAlert type="info" icon={<IconInfo size="md" />}>
- {t(
- "Web vitals is a new beta feature for organizations who have turned on Early Adopter in their account settings. We'd love to hear any feedback you have at"
- )}{' '}
- <ExternalLink href="mailto:[email protected]">
- [email protected]
- </ExternalLink>
- </StyledAlert>
- )}
<StyledNavTabs>
<ListLink
to={summaryTarget}
@@ -171,7 +157,6 @@ class TransactionHeader extends React.Component<Props> {
isActive={() => currentTab === Tab.RealUserMonitoring}
>
{t('Web Vitals')}
- <FeatureBadge type="beta" />
</ListLink>
)}
</StyledNavTabs>
@@ -184,11 +169,6 @@ class TransactionHeader extends React.Component<Props> {
}
}
-const StyledAlert = styled(Alert)`
- /* Makes sure the alert is pushed into another row */
- width: 100%;
-`;
-
const StyledNavTabs = styled(NavTabs)`
margin-bottom: 0;
/* Makes sure the tabs are pushed into another row */
|
96d06cb016078b42abcf52fe43712feb7a1938ef
|
2022-09-30 05:13:36
|
Evan Purkhiser
|
ref(js): Better comments on note/input props (#39494)
| false
|
Better comments on note/input props (#39494)
|
ref
|
diff --git a/static/app/components/activity/note/input.tsx b/static/app/components/activity/note/input.tsx
index 39c156ad8b88f1..b4d3fa5ea2072f 100644
--- a/static/app/components/activity/note/input.tsx
+++ b/static/app/components/activity/note/input.tsx
@@ -21,9 +21,18 @@ import mentionStyle from './mentionStyle';
import {CreateError, MentionChangeEvent, Mentioned} from './types';
type Props = {
+ /**
+ * Is the note saving?
+ */
busy?: boolean;
+ /**
+ * Display an error message
+ */
error?: boolean;
errorJSON?: CreateError | null;
+ /**
+ * Minimum height of the edit area
+ */
minHeight?: number;
/**
* This is the id of the server's note object and is meant to indicate that
|
43d481e1db45fab8157cfab680d4e4a1fedeac0c
|
2021-09-29 22:17:46
|
Chris Fuller
|
feat(workflow): Team Alerts Triggered API (#28816)
| false
|
Team Alerts Triggered API (#28816)
|
feat
|
diff --git a/src/sentry/api/endpoints/team_alerts_triggered.py b/src/sentry/api/endpoints/team_alerts_triggered.py
new file mode 100644
index 00000000000000..9058589f65b2ad
--- /dev/null
+++ b/src/sentry/api/endpoints/team_alerts_triggered.py
@@ -0,0 +1,61 @@
+from datetime import timedelta
+
+from django.db.models import Count, Q
+from django.db.models.functions import TruncDay
+from rest_framework.response import Response
+
+from sentry.api.base import EnvironmentMixin
+from sentry.api.bases.team import TeamEndpoint
+from sentry.api.utils import get_date_range_from_params
+from sentry.incidents.models import (
+ IncidentActivity,
+ IncidentActivityType,
+ IncidentProject,
+ IncidentStatus,
+)
+from sentry.models import Project
+
+
+class TeamAlertsTriggeredEndpoint(TeamEndpoint, EnvironmentMixin):
+ def get(self, request, team):
+ """
+ Return a time-bucketed (by day) count of triggered alerts owned by a given team.
+ """
+ project_list = Project.objects.get_for_team_ids([team.id])
+ owner_ids = [team.actor_id] + list(team.member_set.values_list("user__actor_id", flat=True))
+ start, end = get_date_range_from_params(request.GET)
+ bucketed_alert_counts = (
+ IncidentActivity.objects.filter(
+ (
+ Q(type=IncidentActivityType.CREATED.value)
+ | Q(
+ type=IncidentActivityType.STATUS_CHANGE.value,
+ value__in=[
+ IncidentStatus.OPEN,
+ IncidentStatus.CRITICAL,
+ IncidentStatus.WARNING,
+ ],
+ )
+ ),
+ incident__alert_rule__owner__in=owner_ids,
+ incident_id__in=IncidentProject.objects.filter(project__in=project_list).values(
+ "incident_id"
+ ),
+ date_added__gte=start,
+ date_added__lte=end,
+ )
+ .annotate(bucket=TruncDay("date_added"))
+ .values("bucket")
+ .annotate(count=Count("id"))
+ )
+
+ counts = {str(r["bucket"].replace(tzinfo=None)): r["count"] for r in bucketed_alert_counts}
+ current_day = start.replace(
+ hour=0, minute=0, second=0, microsecond=0, tzinfo=None
+ ) + timedelta(days=1)
+ end_day = end.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
+ while current_day <= end_day:
+ counts.setdefault(str(current_day), 0)
+ current_day += timedelta(days=1)
+
+ return Response(counts)
diff --git a/src/sentry/api/urls.py b/src/sentry/api/urls.py
index 4de9f55ce8243b..30964e1e63a73f 100644
--- a/src/sentry/api/urls.py
+++ b/src/sentry/api/urls.py
@@ -396,6 +396,7 @@
from .endpoints.shared_group_details import SharedGroupDetailsEndpoint
from .endpoints.system_health import SystemHealthEndpoint
from .endpoints.system_options import SystemOptionsEndpoint
+from .endpoints.team_alerts_triggered import TeamAlertsTriggeredEndpoint
from .endpoints.team_avatar import TeamAvatarEndpoint
from .endpoints.team_details import TeamDetailsEndpoint
from .endpoints.team_groups_new import TeamGroupsNewEndpoint
@@ -1452,6 +1453,11 @@
TeamGroupsNewEndpoint.as_view(),
name="sentry-api-0-team-groups-new",
),
+ url(
+ r"^(?P<organization_slug>[^\/]+)/(?P<team_slug>[^\/]+)/alerts-triggered/$",
+ TeamAlertsTriggeredEndpoint.as_view(),
+ name="sentry-api-0-team-alerts-triggered",
+ ),
url(
r"^(?P<organization_slug>[^\/]+)/(?P<team_slug>[^\/]+)/(?:issues|groups)/trending/$",
TeamGroupsTrendingEndpoint.as_view(),
diff --git a/src/sentry/models/project.py b/src/sentry/models/project.py
index dc3440c2b72060..7e3aee132ad51d 100644
--- a/src/sentry/models/project.py
+++ b/src/sentry/models/project.py
@@ -86,7 +86,7 @@ def get_for_user_ids(self, user_ids: Sequence[int]) -> QuerySet:
)
def get_for_team_ids(self, team_ids: Sequence[int]) -> QuerySet:
- """Returns the QuerySet of all organizations that a set of Teams have access to."""
+ """Returns the QuerySet of all projects that a set of Teams have access to."""
from sentry.models import ProjectStatus
return self.filter(status=ProjectStatus.VISIBLE, teams__in=team_ids)
diff --git a/tests/sentry/api/endpoints/test_team_alerts_triggered.py b/tests/sentry/api/endpoints/test_team_alerts_triggered.py
new file mode 100644
index 00000000000000..18048d7d46c660
--- /dev/null
+++ b/tests/sentry/api/endpoints/test_team_alerts_triggered.py
@@ -0,0 +1,181 @@
+from freezegun import freeze_time
+
+from sentry.incidents.models import (
+ AlertRuleThresholdType,
+ IncidentActivity,
+ IncidentActivityType,
+ IncidentStatus,
+)
+from sentry.models import ActorTuple
+from sentry.testutils import APITestCase
+from sentry.testutils.helpers.datetime import before_now
+
+
+@freeze_time()
+class TeamAlertsTriggeredTest(APITestCase):
+ endpoint = "sentry-api-0-team-alerts-triggered"
+
+ def test_simple(self):
+ project1 = self.create_project(
+ teams=[self.team], slug="foo"
+ ) # This project will return counts for this team
+ user_owned_rule = self.create_alert_rule(
+ organization=self.organization,
+ projects=[project1],
+ name="user owned rule",
+ query="",
+ aggregate="count()",
+ time_window=1,
+ threshold_type=AlertRuleThresholdType.ABOVE,
+ resolve_threshold=10,
+ threshold_period=1,
+ owner=ActorTuple.from_actor_identifier(self.user.id),
+ )
+ user_owned_incident = self.create_incident(status=20, alert_rule=user_owned_rule)
+ activities = []
+ for i in range(1, 9):
+ activities.append(
+ IncidentActivity(
+ incident=user_owned_incident,
+ type=IncidentActivityType.CREATED.value,
+ value=IncidentStatus.OPEN,
+ date_added=before_now(days=i),
+ )
+ )
+ IncidentActivity.objects.bulk_create(activities)
+
+ self.login_as(user=self.user)
+ response = self.get_success_response(self.team.organization.slug, self.team.slug)
+ assert len(response.data) == 90
+ for i in range(1, 9):
+ assert (
+ response.data[
+ str(
+ before_now(days=i).replace(
+ hour=0, minute=0, second=0, microsecond=0, tzinfo=None
+ )
+ )
+ ]
+ == 1
+ )
+
+ for i in range(10, 90):
+ assert (
+ response.data[
+ str(
+ before_now(days=i).replace(
+ hour=0, minute=0, second=0, microsecond=0, tzinfo=None
+ )
+ )
+ ]
+ == 0
+ )
+
+ response = self.get_success_response(
+ self.team.organization.slug, self.team.slug, statsPeriod="7d"
+ )
+ assert len(response.data) == 7
+ assert (
+ response.data[
+ str(
+ before_now(days=0).replace(
+ hour=0, minute=0, second=0, microsecond=0, tzinfo=None
+ )
+ )
+ ]
+ == 0
+ )
+ for i in range(1, 6):
+ assert (
+ response.data[
+ str(
+ before_now(days=i).replace(
+ hour=0, minute=0, second=0, microsecond=0, tzinfo=None
+ )
+ )
+ ]
+ == 1
+ )
+
+ def test_not_as_simple(self):
+ team_with_user = self.create_team(
+ organization=self.organization, name="Lonely Team", members=[self.user]
+ )
+
+ project1 = self.create_project(
+ teams=[self.team], slug="foo"
+ ) # This project will return counts for this team
+ project2 = self.create_project(
+ # teams=[team_with_user], slug="bar"
+ teams=[team_with_user],
+ slug="bar",
+ ) # but not this project, cause this team isn't on it (but the user is)
+
+ user_owned_rule = self.create_alert_rule(
+ organization=self.organization,
+ projects=[project2],
+ name="user owned rule",
+ query="",
+ aggregate="count()",
+ time_window=1,
+ threshold_type=AlertRuleThresholdType.ABOVE,
+ resolve_threshold=10,
+ threshold_period=1,
+ owner=ActorTuple.from_actor_identifier(self.user.id),
+ )
+ user_owned_incident = self.create_incident(
+ projects=[project2], status=20, alert_rule=user_owned_rule
+ )
+ team_owned_rule = self.create_alert_rule(
+ organization=self.organization,
+ projects=[project1],
+ name="team owned rule",
+ query="",
+ aggregate="count()",
+ time_window=1,
+ threshold_type=AlertRuleThresholdType.ABOVE,
+ resolve_threshold=10,
+ threshold_period=1,
+ owner=ActorTuple.from_actor_identifier(f"team:{self.team.id}"),
+ )
+ team_owned_incident = self.create_incident(
+ projects=[project1], status=20, alert_rule=team_owned_rule
+ )
+ IncidentActivity.objects.create(
+ incident=user_owned_incident,
+ type=IncidentActivityType.CREATED.value,
+ value=IncidentStatus.OPEN,
+ )
+ IncidentActivity.objects.create(
+ incident=team_owned_incident,
+ type=IncidentActivityType.CREATED.value,
+ value=IncidentStatus.OPEN,
+ date_added=before_now(days=2),
+ )
+
+ self.login_as(user=self.user)
+ response = self.get_success_response(self.team.organization.slug, self.team.slug)
+ assert len(response.data) == 90
+ assert (
+ response.data[
+ str(
+ before_now(days=2).replace(
+ hour=0, minute=0, second=0, microsecond=0, tzinfo=None
+ )
+ )
+ ]
+ == 1
+ )
+ # only getting the team owned incident, because the user owned incident is for another project that the team isn't on
+ for i in range(0, 90):
+ if i != 2:
+ assert (
+ response.data[
+ str(
+ before_now(days=i).replace(
+ hour=0, minute=0, second=0, microsecond=0, tzinfo=None
+ )
+ )
+ ]
+ == 0
+ )
|
7bd87da3d893f59d55a04e4bd6e167e47fd19f75
|
2024-04-23 13:08:07
|
ArthurKnaus
|
chore(codeowners): Add metric settings (#69486)
| false
|
Add metric settings (#69486)
|
chore
|
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index c08271a4c61200..687bf1c1efd935 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -462,6 +462,7 @@ static/app/components/events/eventStatisticalDetector/ @getse
/static/app/views/performance/landing/dynamicSamplingMetricsAccuracy.spec.tsx @getsentry/telemetry-experience
/static/app/views/performance/landing/dynamicSamplingMetricsAccuracyAlert.tsx @getsentry/telemetry-experience
/static/app/views/settings/project/dynamicSampling/ @getsentry/telemetry-experience
+/static/app/views/settings/projectMetrics/* @getsentry/telemetry-experience
/static/app/views/onboarding* @getsentry/telemetry-experience
/static/app/components/metrics/ @getsentry/telemetry-experience
|
3ee64990210a5140b211a873cc1da28e62c9fb63
|
2022-09-30 23:56:20
|
Scott Cooper
|
ref(ui): Convert stacktracelink modal to FC (#39500)
| false
|
Convert stacktracelink modal to FC (#39500)
|
ref
|
diff --git a/static/app/components/events/interfaces/frame/stacktraceLinkModal.tsx b/static/app/components/events/interfaces/frame/stacktraceLinkModal.tsx
index 105a8fcbf1a8a0..336a0ce6cdc38a 100644
--- a/static/app/components/events/interfaces/frame/stacktraceLinkModal.tsx
+++ b/static/app/components/events/interfaces/frame/stacktraceLinkModal.tsx
@@ -1,58 +1,55 @@
-import {Component, Fragment} from 'react';
+import {Fragment, useState} from 'react';
import styled from '@emotion/styled';
import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
import {ModalRenderProps} from 'sentry/actionCreators/modal';
-import {Client} from 'sentry/api';
import Alert from 'sentry/components/alert';
import Button from 'sentry/components/button';
-import ButtonBar from 'sentry/components/buttonBar';
import InputField from 'sentry/components/forms/inputField';
import {t, tct} from 'sentry/locale';
import space from 'sentry/styles/space';
-import {Integration, Organization, Project} from 'sentry/types';
+import type {Integration, Organization, Project} from 'sentry/types';
import {
getIntegrationIcon,
trackIntegrationAnalytics,
} from 'sentry/utils/integrationUtil';
-import withApi from 'sentry/utils/withApi';
+import useApi from 'sentry/utils/useApi';
-type Props = ModalRenderProps & {
- api: Client;
+interface StacktraceLinkModalProps extends ModalRenderProps {
filename: string;
integrations: Integration[];
onSubmit: () => void;
organization: Organization;
project: Project;
-};
-
-type State = {
- sourceCodeInput: string;
-};
+}
-class StacktraceLinkModal extends Component<Props, State> {
- state: State = {
- sourceCodeInput: '',
+function StacktraceLinkModal({
+ closeModal,
+ onSubmit,
+ organization,
+ integrations,
+ filename,
+ project,
+ Header,
+ Body,
+}: StacktraceLinkModalProps) {
+ const api = useApi();
+ const [sourceCodeInput, setSourceCodeInput] = useState('');
+
+ const onHandleChange = (input: string) => {
+ setSourceCodeInput(input);
};
- onHandleChange(sourceCodeInput: string) {
- this.setState({
- sourceCodeInput,
- });
- }
-
- onManualSetup(provider: string) {
+ function onManualSetup(provider: string) {
trackIntegrationAnalytics('integrations.stacktrace_manual_option_clicked', {
view: 'stacktrace_issue_details',
setup_type: 'manual',
provider,
- organization: this.props.organization,
+ organization,
});
}
- handleSubmit = async () => {
- const {sourceCodeInput} = this.state;
- const {api, closeModal, filename, onSubmit, organization, project} = this.props;
+ const handleSubmit = async () => {
trackIntegrationAnalytics('integrations.stacktrace_submit_config', {
setup_type: 'automatic',
view: 'stacktrace_issue_details',
@@ -99,106 +96,98 @@ class StacktraceLinkModal extends Component<Props, State> {
}
};
- render() {
- const {sourceCodeInput} = this.state;
- const {Header, Body, filename, integrations, organization} = this.props;
- const baseUrl = `/settings/${organization.slug}/integrations`;
-
- return (
- <Fragment>
- <Header closeButton>{t('Link Stack Trace To Source Code')}</Header>
- <Body>
- <ModalContainer>
- <div>
- <h6>{t('Automatic Setup')}</h6>
- {tct(
- 'Enter the source code URL corresponding to stack trace filename [filename] so we can automatically set up stack trace linking for this project.',
- {
- filename: <code>{filename}</code>,
- }
- )}
- </div>
- <SourceCodeInput>
- <StyledInputField
- inline={false}
- flexibleControlStateSize
- stacked
- name="source-code-input"
- type="text"
- value={sourceCodeInput}
- onChange={val => this.onHandleChange(val)}
- placeholder={t(
- `https://github.com/helloworld/Hello-World/blob/master/${filename}`
- )}
- />
- <ButtonBar>
- <Button
- data-test-id="quick-setup-button"
- type="button"
- onClick={() => this.handleSubmit()}
- >
- {t('Submit')}
- </Button>
- </ButtonBar>
- </SourceCodeInput>
- <div>
- <h6>{t('Manual Setup')}</h6>
- <Alert type="warning">
- {t(
- 'We recommend this for more complicated configurations, like projects with multiple repositories.'
- )}
- </Alert>
+ return (
+ <Fragment>
+ <Header closeButton>
+ <h4>{t('Link Stack Trace To Source Code')}</h4>
+ </Header>
+ <Body>
+ <ModalContainer>
+ <div>
+ <h6>{t('Automatic Setup')}</h6>
+ {tct(
+ 'Enter the source code URL corresponding to stack trace filename [filename] so we can automatically set up stack trace linking for this project.',
+ {
+ filename: <StyledCode>{filename}</StyledCode>,
+ }
+ )}
+ </div>
+ <SourceCodeInput>
+ <StyledInputField
+ inline={false}
+ flexibleControlStateSize
+ stacked
+ name="source-code-input"
+ type="text"
+ value={sourceCodeInput}
+ onChange={onHandleChange}
+ placeholder={`https://github.com/helloworld/Hello-World/blob/master/${filename}`}
+ />
+ <Button type="button" onClick={handleSubmit}>
+ {t('Submit')}
+ </Button>
+ </SourceCodeInput>
+ <div>
+ <h6>{t('Manual Setup')}</h6>
+ <Alert type="warning">
{t(
- "To manually configure stack trace linking, select the integration you'd like to use for mapping:"
+ 'We recommend this for more complicated configurations, like projects with multiple repositories.'
)}
- </div>
- <ManualSetup>
- {integrations.map(integration => (
- <Button
- key={integration.id}
- type="button"
- onClick={() => this.onManualSetup(integration.provider.key)}
- to={`${baseUrl}/${integration.provider.key}/${integration.id}/?tab=codeMappings&referrer=stacktrace-issue-details`}
- >
- {getIntegrationIcon(integration.provider.key)}
- <IntegrationName>{integration.name}</IntegrationName>
- </Button>
- ))}
- </ManualSetup>
- </ModalContainer>
- </Body>
- </Fragment>
- );
- }
+ </Alert>
+ {t(
+ "To manually configure stack trace linking, select the integration you'd like to use for mapping:"
+ )}
+ </div>
+ <ManualSetup>
+ {integrations.map(integration => (
+ <Button
+ key={integration.id}
+ type="button"
+ onClick={() => onManualSetup(integration.provider.key)}
+ to={{
+ pathname: `/settings/${organization.slug}/integrations/${integration.provider.key}/${integration.id}/`,
+ query: {tab: 'codeMappings', referrer: 'stacktrace-issue-details'},
+ }}
+ >
+ {getIntegrationIcon(integration.provider.key)}
+ <IntegrationName>{integration.name}</IntegrationName>
+ </Button>
+ ))}
+ </ManualSetup>
+ </ModalContainer>
+ </Body>
+ </Fragment>
+ );
}
-const SourceCodeInput = styled('div')`
+const ModalContainer = styled('div')`
display: grid;
- grid-template-columns: 5fr 1fr;
- gap: ${space(1)};
+ gap: ${space(3)};
`;
-const ManualSetup = styled('div')`
- display: grid;
- gap: ${space(1)};
- justify-items: center;
+const StyledCode = styled('code')`
+ word-break: break-word;
`;
-const ModalContainer = styled('div')`
- display: grid;
- gap: ${space(3)};
+const SourceCodeInput = styled('div')`
+ display: flex;
+ gap: ${space(1)};
+`;
- code {
- word-break: break-word;
- }
+const ManualSetup = styled('div')`
+ display: flex;
+ gap: ${space(1)};
+ flex-direction: column;
+ align-items: center;
`;
const StyledInputField = styled(InputField)`
padding: 0px;
+ flex-grow: 1;
`;
const IntegrationName = styled('p')`
padding-left: 10px;
`;
-export default withApi(StacktraceLinkModal);
+export default StacktraceLinkModal;
|
1933148aa60a3ccbdd45f21cbacb2a4d7b354ea6
|
2023-06-16 23:29:33
|
Scott Cooper
|
test(ui): Return router props from initializeOrg (#49372)
| false
|
Return router props from initializeOrg (#49372)
|
test
|
diff --git a/static/app/components/createAlertButton.spec.jsx b/static/app/components/createAlertButton.spec.jsx
index c3180a4271edb9..1991cd29c69ad0 100644
--- a/static/app/components/createAlertButton.spec.jsx
+++ b/static/app/components/createAlertButton.spec.jsx
@@ -171,9 +171,9 @@ describe('CreateAlertFromViewButton', () => {
expect(navigateTo).toHaveBeenCalledWith(
`/organizations/org-slug/alerts/wizard/?`,
expect.objectContaining({
- params: {
+ params: expect.objectContaining({
orgId: 'org-slug',
- },
+ }),
})
);
});
diff --git a/static/app/components/datePageFilter.spec.tsx b/static/app/components/datePageFilter.spec.tsx
index e70da75da0701e..dafba1c8e4df28 100644
--- a/static/app/components/datePageFilter.spec.tsx
+++ b/static/app/components/datePageFilter.spec.tsx
@@ -6,9 +6,6 @@ import OrganizationStore from 'sentry/stores/organizationStore';
import PageFiltersStore from 'sentry/stores/pageFiltersStore';
const {organization, router, routerContext} = initializeOrg({
- organization: {},
- project: undefined,
- projects: undefined,
router: {
location: {
query: {},
diff --git a/static/app/components/events/eventReplay/replayPreview.spec.tsx b/static/app/components/events/eventReplay/replayPreview.spec.tsx
index d7954e799cf7dc..13379bfca60224 100644
--- a/static/app/components/events/eventReplay/replayPreview.spec.tsx
+++ b/static/app/components/events/eventReplay/replayPreview.spec.tsx
@@ -60,9 +60,6 @@ jest.mock('sentry/utils/replays/hooks/useReplayData', () => {
const render: typeof baseRender = children => {
const {router, routerContext} = initializeOrg({
- organization: {},
- project: TestStubs.Project(),
- projects: [TestStubs.Project()],
router: {
routes: [
{path: '/'},
diff --git a/static/app/components/organizations/datePageFilter.spec.tsx b/static/app/components/organizations/datePageFilter.spec.tsx
index c07cb008c6835d..2104da01d5518f 100644
--- a/static/app/components/organizations/datePageFilter.spec.tsx
+++ b/static/app/components/organizations/datePageFilter.spec.tsx
@@ -7,9 +7,6 @@ import OrganizationStore from 'sentry/stores/organizationStore';
import PageFiltersStore from 'sentry/stores/pageFiltersStore';
const {organization, router, routerContext} = initializeOrg({
- organization: {},
- project: undefined,
- projects: undefined,
router: {
location: {
query: {},
@@ -132,9 +129,6 @@ describe('DatePageFilter', function () {
router: desyncRouter,
routerContext: desyncRouterContext,
} = initializeOrg({
- organization: {},
- project: undefined,
- projects: undefined,
router: {
location: {
// the datetime parameters need to be non-null for desync detection to work
diff --git a/static/app/views/alerts/rules/metric/details/index.spec.tsx b/static/app/views/alerts/rules/metric/details/index.spec.tsx
index e24d61aa30ce2b..1551d360dc8539 100644
--- a/static/app/views/alerts/rules/metric/details/index.spec.tsx
+++ b/static/app/views/alerts/rules/metric/details/index.spec.tsx
@@ -36,7 +36,7 @@ describe('MetricAlertDetails', () => {
});
it('renders', async () => {
- const {routerContext, organization, router} = initializeOrg();
+ const {routerContext, organization, routerProps} = initializeOrg();
const incident = TestStubs.Incident();
const rule = TestStubs.MetricRule({
projects: [project.slug],
@@ -55,11 +55,7 @@ describe('MetricAlertDetails', () => {
render(
<MetricAlertDetails
organization={organization}
- route={{}}
- router={router}
- routes={router.routes}
- routeParams={router.params}
- location={router.location}
+ {...routerProps}
params={{ruleId: rule.id}}
/>,
{context: routerContext, organization}
@@ -81,7 +77,7 @@ describe('MetricAlertDetails', () => {
});
it('renders selected incident', async () => {
- const {routerContext, organization, router} = initializeOrg();
+ const {routerContext, organization, router, routerProps} = initializeOrg();
const rule = TestStubs.MetricRule({projects: [project.slug]});
const incident = TestStubs.Incident();
@@ -106,10 +102,7 @@ describe('MetricAlertDetails', () => {
render(
<MetricAlertDetails
organization={organization}
- route={{}}
- router={router}
- routes={router.routes}
- routeParams={router.params}
+ {...routerProps}
location={{...router.location, query: {alert: incident.id}}}
params={{ruleId: rule.id}}
/>,
diff --git a/static/app/views/alerts/rules/metric/duplicate.spec.tsx b/static/app/views/alerts/rules/metric/duplicate.spec.tsx
index c64fb6bdfae65d..8898fafcb39af0 100644
--- a/static/app/views/alerts/rules/metric/duplicate.spec.tsx
+++ b/static/app/views/alerts/rules/metric/duplicate.spec.tsx
@@ -61,7 +61,7 @@ describe('Incident Rules Duplicate', function () {
});
rule.resolveThreshold = 50;
- const {organization, project, router} = initializeOrg({
+ const {organization, project, routerProps} = initializeOrg({
organization: {
access: ['alerts:write'],
},
@@ -69,7 +69,7 @@ describe('Incident Rules Duplicate', function () {
params: {},
location: {
query: {
- createFromDuplicate: true,
+ createFromDuplicate: 'true',
duplicateRuleId: `${rule.id}`,
},
},
@@ -87,15 +87,10 @@ describe('Incident Rules Duplicate', function () {
<Fragment>
<GlobalModal />
<MetricRulesDuplicate
- params={{}}
- route={{}}
- routeParams={router.params}
- router={router}
- routes={router.routes}
- location={router.location}
organization={organization}
project={project}
userTeamIds={[]}
+ {...routerProps}
/>
</Fragment>
);
@@ -126,7 +121,7 @@ describe('Incident Rules Duplicate', function () {
desc: 'Send a Slack notification to #feed-ecosystem',
});
- const {organization, project, router} = initializeOrg({
+ const {organization, project, routerProps} = initializeOrg({
organization: {
access: ['alerts:write'],
},
@@ -134,7 +129,7 @@ describe('Incident Rules Duplicate', function () {
params: {},
location: {
query: {
- createFromDuplicate: true,
+ createFromDuplicate: 'true',
duplicateRuleId: `${rule.id}`,
},
},
@@ -150,15 +145,10 @@ describe('Incident Rules Duplicate', function () {
render(
<MetricRulesDuplicate
- params={{}}
- route={{}}
- routeParams={router.params}
- router={router}
- routes={router.routes}
- location={router.location}
organization={organization}
project={project}
userTeamIds={[]}
+ {...routerProps}
/>
);
diff --git a/static/app/views/alerts/wizard/index.spec.tsx b/static/app/views/alerts/wizard/index.spec.tsx
index ddbda89beb608b..b370e89061192c 100644
--- a/static/app/views/alerts/wizard/index.spec.tsx
+++ b/static/app/views/alerts/wizard/index.spec.tsx
@@ -5,7 +5,7 @@ import AlertWizard from 'sentry/views/alerts/wizard/index';
describe('AlertWizard', () => {
it('sets crash free dataset to metrics', async () => {
- const {organization, project, router, routerContext} = initializeOrg({
+ const {organization, project, routerProps, routerContext} = initializeOrg({
organization: {
features: [
'alert-crash-free-metrics',
@@ -15,20 +15,12 @@ describe('AlertWizard', () => {
],
access: ['org:write', 'alerts:write'],
},
- project: undefined,
- projects: undefined,
- router: undefined,
});
render(
<AlertWizard
organization={organization}
- route={{}}
- router={router}
- routes={router.routes}
- routeParams={router.params}
- location={router.location}
- params={{projectId: project.slug}}
projectId={project.slug}
+ {...routerProps}
/>,
{context: routerContext, organization}
);
diff --git a/static/app/views/discover/results.spec.tsx b/static/app/views/discover/results.spec.tsx
index 2d0de7db5164b4..208fc3730960cf 100644
--- a/static/app/views/discover/results.spec.tsx
+++ b/static/app/views/discover/results.spec.tsx
@@ -478,7 +478,7 @@ describe('Results', function () {
query: {
...generateFields(),
statsPeriod: '60d',
- project: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
+ project: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].map(String),
},
},
},
@@ -547,7 +547,11 @@ describe('Results', function () {
organization,
router: {
location: {
- query: {...generateFields(), statsPeriod: '90d', project: [1, 2, 3, 4]},
+ query: {
+ ...generateFields(),
+ statsPeriod: '90d',
+ project: [1, 2, 3, 4].map(String),
+ },
},
},
});
@@ -644,7 +648,7 @@ describe('Results', function () {
query: {
id: '1',
statsPeriod: '7d',
- project: [2],
+ project: ['2'],
environment: ['production'],
},
},
@@ -1043,7 +1047,7 @@ describe('Results', function () {
const initialData = initializeOrg({
organization,
router: {
- location: {query: {fromMetric: true, id: '1'}},
+ location: {query: {fromMetric: 'true', id: '1'}},
},
});
@@ -1080,7 +1084,7 @@ describe('Results', function () {
const initialData = initializeOrg({
organization,
router: {
- location: {query: {showUnparameterizedBanner: true, id: '1'}},
+ location: {query: {showUnparameterizedBanner: 'true', id: '1'}},
},
});
diff --git a/static/app/views/issueDetails/groupTagValues.spec.jsx b/static/app/views/issueDetails/groupTagValues.spec.jsx
index 5c2d55d7dd37c2..93cfe3bb9ea9e7 100644
--- a/static/app/views/issueDetails/groupTagValues.spec.jsx
+++ b/static/app/views/issueDetails/groupTagValues.spec.jsx
@@ -8,9 +8,6 @@ const tags = TestStubs.Tags();
function init(tagKey) {
return initializeOrg({
- organization: {},
- project: undefined,
- projects: undefined,
router: {
location: {
query: {},
diff --git a/static/app/views/onboarding/onboarding.spec.tsx b/static/app/views/onboarding/onboarding.spec.tsx
index 7d4c92638396e7..e800c4d6f46386 100644
--- a/static/app/views/onboarding/onboarding.spec.tsx
+++ b/static/app/views/onboarding/onboarding.spec.tsx
@@ -22,7 +22,7 @@ describe('Onboarding', function () {
step: 'welcome',
};
- const {router, route, routerContext, organization} = initializeOrg({
+ const {routerProps, routerContext, organization} = initializeOrg({
router: {
params: routeParams,
},
@@ -30,14 +30,7 @@ describe('Onboarding', function () {
render(
<OnboardingContextProvider>
- <Onboarding
- router={router}
- location={router.location}
- params={routeParams}
- routes={router.routes}
- routeParams={router.params}
- route={route}
- />
+ <Onboarding {...routerProps} />
</OnboardingContextProvider>,
{
context: routerContext,
@@ -54,7 +47,7 @@ describe('Onboarding', function () {
step: 'select-platform',
};
- const {router, route, routerContext, organization} = initializeOrg({
+ const {routerProps, routerContext, organization} = initializeOrg({
router: {
params: routeParams,
},
@@ -62,14 +55,7 @@ describe('Onboarding', function () {
render(
<OnboardingContextProvider>
- <Onboarding
- router={router}
- location={router.location}
- params={routeParams}
- routes={router.routes}
- routeParams={router.params}
- route={route}
- />
+ <Onboarding {...routerProps} />
</OnboardingContextProvider>,
{
context: routerContext,
@@ -93,7 +79,7 @@ describe('Onboarding', function () {
step: 'setup-docs',
};
- const {router, route, routerContext, organization} = initializeOrg({
+ const {routerProps, routerContext, organization} = initializeOrg({
router: {
params: routeParams,
},
@@ -146,14 +132,7 @@ describe('Onboarding', function () {
},
}}
>
- <Onboarding
- router={router}
- location={router.location}
- params={routeParams}
- routes={router.routes}
- routeParams={router.params}
- route={route}
- />
+ <Onboarding {...routerProps} />
</OnboardingContextProvider>,
{
context: routerContext,
@@ -179,7 +158,7 @@ describe('Onboarding', function () {
step: 'setup-docs',
};
- const {router, route, routerContext, organization} = initializeOrg({
+ const {routerProps, routerContext, organization} = initializeOrg({
organization: {
features: ['onboarding-project-deletion-on-back-click'],
},
@@ -235,14 +214,7 @@ describe('Onboarding', function () {
},
}}
>
- <Onboarding
- router={router}
- location={router.location}
- params={routeParams}
- routes={router.routes}
- routeParams={router.params}
- route={route}
- />
+ <Onboarding {...routerProps} />
</OnboardingContextProvider>,
{
context: routerContext,
@@ -278,7 +250,7 @@ describe('Onboarding', function () {
step: 'setup-docs',
};
- const {router, route, routerContext, organization} = initializeOrg({
+ const {routerProps, routerContext, organization} = initializeOrg({
organization: {
features: ['onboarding-project-deletion-on-back-click'],
},
@@ -334,14 +306,7 @@ describe('Onboarding', function () {
},
}}
>
- <Onboarding
- router={router}
- location={router.location}
- params={routeParams}
- routes={router.routes}
- routeParams={router.params}
- route={route}
- />
+ <Onboarding {...routerProps} />
</OnboardingContextProvider>,
{
context: routerContext,
@@ -368,7 +333,7 @@ describe('Onboarding', function () {
step: 'select-platform',
};
- const {router, route, routerContext, organization} = initializeOrg({
+ const {routerProps, routerContext, organization} = initializeOrg({
organization: {
features: ['onboarding-sdk-selection'],
},
@@ -379,14 +344,7 @@ describe('Onboarding', function () {
render(
<OnboardingContextProvider>
- <Onboarding
- router={router}
- location={router.location}
- params={routeParams}
- routes={router.routes}
- routeParams={router.params}
- route={route}
- />
+ <Onboarding {...routerProps} />
</OnboardingContextProvider>,
{
context: routerContext,
@@ -414,7 +372,7 @@ describe('Onboarding', function () {
step: 'select-platform',
};
- const {router, route, routerContext, organization} = initializeOrg({
+ const {routerProps, routerContext, organization} = initializeOrg({
organization: {
features: ['onboarding-sdk-selection'],
},
@@ -425,14 +383,7 @@ describe('Onboarding', function () {
render(
<OnboardingContextProvider>
- <Onboarding
- router={router}
- location={router.location}
- params={routeParams}
- routes={router.routes}
- routeParams={router.params}
- route={route}
- />
+ <Onboarding {...routerProps} />
</OnboardingContextProvider>,
{
context: routerContext,
diff --git a/static/app/views/performance/transactionSummary/transactionEvents/content.spec.tsx b/static/app/views/performance/transactionSummary/transactionEvents/content.spec.tsx
index 3c3e416de2064d..7453291076c04f 100644
--- a/static/app/views/performance/transactionSummary/transactionEvents/content.spec.tsx
+++ b/static/app/views/performance/transactionSummary/transactionEvents/content.spec.tsx
@@ -26,7 +26,7 @@ function initializeData() {
location: {
query: {
transaction: '/performance',
- project: 1,
+ project: '1',
transactionCursor: '1:0:0',
},
},
diff --git a/static/app/views/performance/transactionSummary/transactionEvents/eventsTable.spec.tsx b/static/app/views/performance/transactionSummary/transactionEvents/eventsTable.spec.tsx
index 9c3f98bacea81c..94f2bd6e32fcf1 100644
--- a/static/app/views/performance/transactionSummary/transactionEvents/eventsTable.spec.tsx
+++ b/static/app/views/performance/transactionSummary/transactionEvents/eventsTable.spec.tsx
@@ -68,7 +68,7 @@ function initializeData({features: additionalFeatures = []}: Data = {}) {
location: {
query: {
transaction: '/performance',
- project: 1,
+ project: '1',
transactionCursor: '1:0:0',
},
},
diff --git a/static/app/views/performance/vitalDetail/index.spec.tsx b/static/app/views/performance/vitalDetail/index.spec.tsx
index 75fe421172e118..173b9c3aa7b9be 100644
--- a/static/app/views/performance/vitalDetail/index.spec.tsx
+++ b/static/app/views/performance/vitalDetail/index.spec.tsx
@@ -28,7 +28,7 @@ const {
router: {
location: {
query: {
- project: 1,
+ project: '1',
},
},
},
@@ -259,7 +259,7 @@ describe('Performance > VitalDetail', function () {
expect(browserHistory.push).toHaveBeenCalledWith({
pathname: undefined,
query: {
- project: 1,
+ project: '1',
statsPeriod: '14d',
query: 'user.email:uhoh*',
},
diff --git a/static/app/views/settings/projectSecurityHeaders/expectCt.spec.tsx b/static/app/views/settings/projectSecurityHeaders/expectCt.spec.tsx
index 1deafd3dfe0400..15f0369adaad73 100644
--- a/static/app/views/settings/projectSecurityHeaders/expectCt.spec.tsx
+++ b/static/app/views/settings/projectSecurityHeaders/expectCt.spec.tsx
@@ -4,7 +4,7 @@ import {render} from 'sentry-test/reactTestingLibrary';
import ProjectExpectCtReports from 'sentry/views/settings/projectSecurityHeaders/expectCt';
describe('ProjectExpectCtReports', function () {
- const {router, organization, project} = initializeOrg();
+ const {organization, project, routerProps} = initializeOrg();
const url = `/projects/${organization.slug}/${project.slug}/expect-ct/`;
beforeEach(function () {
@@ -19,11 +19,7 @@ describe('ProjectExpectCtReports', function () {
it('renders', function () {
const {container} = render(
<ProjectExpectCtReports
- route={{}}
- routeParams={{}}
- router={router}
- routes={router.routes}
- params={{projectId: project.slug}}
+ {...routerProps}
location={TestStubs.location({pathname: url})}
organization={organization}
/>
diff --git a/static/app/views/settings/projectSourceMaps/projectSourceMaps.spec.tsx b/static/app/views/settings/projectSourceMaps/projectSourceMaps.spec.tsx
index 917c1056562f70..029a010e823561 100644
--- a/static/app/views/settings/projectSourceMaps/projectSourceMaps.spec.tsx
+++ b/static/app/views/settings/projectSourceMaps/projectSourceMaps.spec.tsx
@@ -62,7 +62,7 @@ function renderDebugIdBundlesMockRequests({
describe('ProjectSourceMaps', function () {
describe('Release Bundles', function () {
it('renders default state', async function () {
- const {organization, route, project, router, routerContext} = initializeOrg({
+ const {organization, project, router, routerContext, routerProps} = initializeOrg({
router: {
location: {
query: {},
@@ -70,7 +70,6 @@ describe('ProjectSourceMaps', function () {
initializeOrg().project.slug
}/source-maps/release-bundles/`,
},
- params: {},
},
});
@@ -79,18 +78,10 @@ describe('ProjectSourceMaps', function () {
projectSlug: project.slug,
});
- render(
- <ProjectSourceMaps
- location={routerContext.context.location}
- project={project}
- route={route}
- routeParams={{orgId: organization.slug, projectId: project.slug}}
- router={router}
- routes={[]}
- params={{orgId: organization.slug, projectId: project.slug}}
- />,
- {context: routerContext, organization}
- );
+ render(<ProjectSourceMaps project={project} {...routerProps} />, {
+ context: routerContext,
+ organization,
+ });
// Title
expect(screen.getByRole('heading', {name: 'Source Maps'})).toBeInTheDocument();
@@ -169,7 +160,7 @@ describe('ProjectSourceMaps', function () {
});
it('renders empty state', async function () {
- const {organization, route, project, router, routerContext} = initializeOrg({
+ const {organization, project, routerContext, routerProps} = initializeOrg({
router: {
location: {
query: {},
@@ -177,7 +168,6 @@ describe('ProjectSourceMaps', function () {
initializeOrg().project.slug
}/source-maps/release-bundles/`,
},
- params: {},
},
});
@@ -187,18 +177,10 @@ describe('ProjectSourceMaps', function () {
empty: true,
});
- render(
- <ProjectSourceMaps
- location={routerContext.context.location}
- project={project}
- route={route}
- routeParams={{orgId: organization.slug, projectId: project.slug}}
- router={router}
- routes={[]}
- params={{orgId: organization.slug, projectId: project.slug}}
- />,
- {context: routerContext, organization}
- );
+ render(<ProjectSourceMaps project={project} {...routerProps} />, {
+ context: routerContext,
+ organization,
+ });
expect(
await screen.findByText('No release bundles found for this project.')
@@ -208,7 +190,7 @@ describe('ProjectSourceMaps', function () {
describe('Artifact Bundles', function () {
it('renders default state', async function () {
- const {organization, route, project, router, routerContext} = initializeOrg({
+ const {organization, project, routerContext, router, routerProps} = initializeOrg({
router: {
location: {
query: {},
@@ -216,7 +198,6 @@ describe('ProjectSourceMaps', function () {
initializeOrg().project.slug
}/source-maps/artifact-bundles/`,
},
- params: {},
},
});
@@ -225,18 +206,10 @@ describe('ProjectSourceMaps', function () {
projectSlug: project.slug,
});
- render(
- <ProjectSourceMaps
- location={routerContext.context.location}
- project={project}
- route={route}
- routeParams={{orgId: organization.slug, projectId: project.slug}}
- router={router}
- routes={[]}
- params={{orgId: organization.slug, projectId: project.slug}}
- />,
- {context: routerContext, organization}
- );
+ render(<ProjectSourceMaps project={project} {...routerProps} />, {
+ context: routerContext,
+ organization,
+ });
// Title
expect(screen.getByRole('heading', {name: 'Source Maps'})).toBeInTheDocument();
@@ -326,7 +299,7 @@ describe('ProjectSourceMaps', function () {
});
it('renders empty state', async function () {
- const {organization, route, project, router, routerContext} = initializeOrg({
+ const {organization, project, routerProps, routerContext} = initializeOrg({
router: {
location: {
query: {},
@@ -334,7 +307,6 @@ describe('ProjectSourceMaps', function () {
initializeOrg().project.slug
}/source-maps/artifact-bundles/`,
},
- params: {},
},
});
@@ -344,18 +316,10 @@ describe('ProjectSourceMaps', function () {
empty: true,
});
- render(
- <ProjectSourceMaps
- location={routerContext.context.location}
- project={project}
- route={route}
- routeParams={{orgId: organization.slug, projectId: project.slug}}
- router={router}
- routes={[]}
- params={{orgId: organization.slug, projectId: project.slug}}
- />,
- {context: routerContext, organization}
- );
+ render(<ProjectSourceMaps project={project} {...routerProps} />, {
+ context: routerContext,
+ organization,
+ });
expect(
await screen.findByText('No artifact bundles found for this project.')
diff --git a/tests/js/sentry-test/initializeOrg.tsx b/tests/js/sentry-test/initializeOrg.tsx
index af5f2db051bae5..9266a69788d5e1 100644
--- a/tests/js/sentry-test/initializeOrg.tsx
+++ b/tests/js/sentry-test/initializeOrg.tsx
@@ -1,5 +1,18 @@
+import type {RouteComponent, RouteComponentProps} from 'react-router';
+import type {Location} from 'history';
+
import type {Organization, Project} from 'sentry/types';
+// Workaround react-router PlainRoute type not covering redirect routes.
+type RouteShape = {
+ childRoutes?: RouteShape[];
+ component?: RouteComponent;
+ from?: string;
+ indexRoute?: RouteShape;
+ name?: string;
+ path?: string;
+};
+
/**
* Creates stubs for:
* - a project or projects
@@ -7,7 +20,7 @@ import type {Organization, Project} from 'sentry/types';
* - router
* - context that contains org + projects + router
*/
-export function initializeOrg({
+export function initializeOrg<RouterParams = {orgId: string; projectId: string}>({
organization: additionalOrg,
project: additionalProject,
projects: additionalProjects,
@@ -16,7 +29,7 @@ export function initializeOrg({
organization?: Partial<Organization>;
project?: Partial<Project>;
projects?: Partial<Project>[];
- router?: any;
+ router?: {location?: Partial<Location>; params?: RouterParams; routes?: RouteShape[]};
} = {}) {
const projects = (
additionalProjects ||
@@ -33,6 +46,7 @@ export function initializeOrg({
...additionalRouter,
params: {
orgId: organization.slug,
+ projectId: projects[0]?.slug,
...additionalRouter?.params,
},
});
@@ -46,13 +60,31 @@ export function initializeOrg({
},
]);
+ /**
+ * A collection of router props that are passed to components by react-router
+ *
+ * Pass custom router params like so:
+ * ```ts
+ * initializeOrg({router: {params: {alertId: '123'}}})
+ * ```
+ */
+ const routerProps: RouteComponentProps<RouterParams, {}> = {
+ params: router.params as any,
+ routeParams: router.params,
+ router,
+ route: router.routes[0],
+ routes: router.routes,
+ location: routerContext.context.location,
+ };
+
return {
organization,
project,
projects,
router,
routerContext,
- // not sure what purpose this serves
+ routerProps,
+ // @deprecated - not sure what purpose this serves
route: {},
};
}
diff --git a/tests/js/sentry-test/performance/initializePerformanceData.ts b/tests/js/sentry-test/performance/initializePerformanceData.ts
index 277a647f54448a..dcff9606103d3a 100644
--- a/tests/js/sentry-test/performance/initializePerformanceData.ts
+++ b/tests/js/sentry-test/performance/initializePerformanceData.ts
@@ -33,7 +33,7 @@ export function initializeData(settings?: InitializeDataSettings) {
features,
projects,
});
- const routerLocation: {query: {project?: number}} = {
+ const routerLocation: {query: {project?: string}} = {
query: {
...query,
},
|
29cedb83155c4c4ea00d2200d175b3bf6ab97d61
|
2020-04-27 17:36:08
|
Armin Ronacher
|
feat(releases): Prevent deletion if a release has health data (#18474)
| false
|
Prevent deletion if a release has health data (#18474)
|
feat
|
diff --git a/src/sentry/api/endpoints/organization_release_details.py b/src/sentry/api/endpoints/organization_release_details.py
index 240d64f9097fd1..58c699e1d0a930 100644
--- a/src/sentry/api/endpoints/organization_release_details.py
+++ b/src/sentry/api/endpoints/organization_release_details.py
@@ -14,13 +14,12 @@
ReleaseHeadCommitSerializer,
ReleaseHeadCommitSerializerDeprecated,
)
-from sentry.models import Activity, Group, Release, ReleaseFile, Project
+from sentry.models import Activity, Release, Project
+from sentry.models.release import UnsafeReleaseDeletion
from sentry.utils.apidocs import scenario, attach_scenarios
from sentry.snuba.sessions import STATS_PERIODS
from sentry.api.endpoints.organization_releases import get_stats_period_detail
-ERR_RELEASE_REFERENCED = "This release is referenced by active issues and cannot be removed."
-
@scenario("RetrieveOrganizationRelease")
def retrieve_organization_release_scenario(runner):
@@ -219,18 +218,9 @@ def delete(self, request, organization, version):
if not self.has_release_permission(request, organization, release):
raise ResourceDoesNotExist
- # we don't want to remove the first_release metadata on the Group, and
- # while people might want to kill a release (maybe to remove files),
- # removing the release is prevented
- if Group.objects.filter(first_release=release).exists():
- return Response({"detail": ERR_RELEASE_REFERENCED}, status=400)
-
- # TODO(dcramer): this needs to happen in the queue as it could be a long
- # and expensive operation
- file_list = ReleaseFile.objects.filter(release=release).select_related("file")
- for releasefile in file_list:
- releasefile.file.delete()
- releasefile.delete()
- release.delete()
+ try:
+ release.safe_delete()
+ except UnsafeReleaseDeletion as e:
+ return Response({"detail": six.text_type(e)}, status=400)
return Response(status=204)
diff --git a/src/sentry/api/endpoints/project_release_details.py b/src/sentry/api/endpoints/project_release_details.py
index bb131554c40cf5..ac7bbb1160b500 100644
--- a/src/sentry/api/endpoints/project_release_details.py
+++ b/src/sentry/api/endpoints/project_release_details.py
@@ -1,5 +1,7 @@
from __future__ import absolute_import
+import six
+
from rest_framework.response import Response
from rest_framework.exceptions import ParseError
@@ -8,16 +10,14 @@
from sentry.api.serializers import serialize
from sentry.api.serializers.rest_framework import ReleaseSerializer
-from sentry.models import Activity, Group, Release, ReleaseFile
+from sentry.models import Activity, Release
+from sentry.models.release import UnsafeReleaseDeletion
from sentry.plugins.interfaces.releasehook import ReleaseHook
from sentry.snuba.sessions import STATS_PERIODS
from sentry.api.endpoints.organization_releases import get_stats_period_detail
-ERR_RELEASE_REFERENCED = "This release is referenced by active issues and cannot be removed."
-
-
class ProjectReleaseDetailsEndpoint(ProjectEndpoint):
permission_classes = (ProjectReleasePermission,)
@@ -152,18 +152,9 @@ def delete(self, request, project, version):
except Release.DoesNotExist:
raise ResourceDoesNotExist
- # we don't want to remove the first_release metadata on the Group, and
- # while people might want to kill a release (maybe to remove files),
- # removing the release is prevented
- if Group.objects.filter(first_release=release).exists():
- return Response({"detail": ERR_RELEASE_REFERENCED}, status=400)
-
- # TODO(dcramer): this needs to happen in the queue as it could be a long
- # and expensive operation
- file_list = ReleaseFile.objects.filter(release=release).select_related("file")
- for releasefile in file_list:
- releasefile.file.delete()
- releasefile.delete()
- release.delete()
+ try:
+ release.safe_delete()
+ except UnsafeReleaseDeletion as e:
+ return Response({"detail": six.text_type(e)}, status=400)
return Response(status=204)
diff --git a/src/sentry/models/release.py b/src/sentry/models/release.py
index d9489f0f85502e..d9194b8eac8bfd 100644
--- a/src/sentry/models/release.py
+++ b/src/sentry/models/release.py
@@ -38,6 +38,14 @@
DB_VERSION_LENGTH = 250
+ERR_RELEASE_REFERENCED = "This release is referenced by active issues and cannot be removed."
+ERR_RELEASE_HEALTH_DATA = "This release has health data and cannot be removed."
+
+
+class UnsafeReleaseDeletion(Exception):
+ pass
+
+
class ReleaseProject(Model):
__core__ = False
@@ -627,3 +635,32 @@ def set_commits(self, commit_list):
kick_off_status_syncs.apply_async(
kwargs={"project_id": group_project_lookup[group_id], "group_id": group_id}
)
+
+ def safe_delete(self):
+ """Deletes a release if possible or raises a `UnsafeReleaseDeletion`
+ exception.
+ """
+ from sentry.models import Group, ReleaseFile
+ from sentry.snuba.sessions import check_has_health_data
+
+ # we don't want to remove the first_release metadata on the Group, and
+ # while people might want to kill a release (maybe to remove files),
+ # removing the release is prevented
+ if Group.objects.filter(first_release=self).exists():
+ raise UnsafeReleaseDeletion(ERR_RELEASE_REFERENCED)
+
+ # We do not allow releases with health data to be deleted because
+ # the upserting from snuba data would create the release again.
+ # We would need to be able to delete this data from snuba which we
+ # can't do yet.
+ project_ids = list(self.projects.values_list("id").all())
+ if check_has_health_data([(p[0], self.version) for p in project_ids]):
+ raise UnsafeReleaseDeletion(ERR_RELEASE_HEALTH_DATA)
+
+ # TODO(dcramer): this needs to happen in the queue as it could be a long
+ # and expensive operation
+ file_list = ReleaseFile.objects.filter(release=self).select_related("file")
+ for releasefile in file_list:
+ releasefile.file.delete()
+ releasefile.delete()
+ self.delete()
|
6ea0afe6bd11aa022dbbfb82792d67c889105216
|
2020-09-09 14:55:06
|
Matej Minar
|
feat(ui): Force releases v2 to everyone (#20585)
| false
|
Force releases v2 to everyone (#20585)
|
feat
|
diff --git a/src/sentry/static/sentry/app/views/releasesV2/utils/index.tsx b/src/sentry/static/sentry/app/views/releasesV2/utils/index.tsx
index b8975a5c2fcb99..f3a2f144be7b1b 100644
--- a/src/sentry/static/sentry/app/views/releasesV2/utils/index.tsx
+++ b/src/sentry/static/sentry/app/views/releasesV2/utils/index.tsx
@@ -4,7 +4,6 @@ import localStorage from 'app/utils/localStorage';
import ConfigStore from 'app/stores/configStore';
import OrganizationStore from 'app/stores/organizationStore';
import {trackAnalyticsEvent} from 'app/utils/analytics';
-import {Client} from 'app/api';
import {stringifyQueryObject, QueryResults} from 'app/utils/tokenizeSearch';
const RELEASES_VERSION_KEY = 'releases:version';
@@ -29,30 +28,14 @@ export const wantsLegacyReleases = () => {
};
export const decideReleasesVersion = async hasNewReleases => {
- const api = new Client();
const {organization} = OrganizationStore.get();
+ // we are forcing everyone to version 2 now, we will delete the codebase behind v1 in a week or so
if (wantsLegacyReleases()) {
- return hasNewReleases(false);
+ switchReleasesVersion('2', organization?.id ?? '0');
}
- if (organization) {
- return hasNewReleases(organization.features.includes('releases-v2'));
- }
-
- // in case there is no organization in the store yet, we fetch it
- // this function is being called from the routes file where we do not have access to much stuff at that point
- // we will be removing this logic once we go GA with releases v2 in a few weeks
- try {
- const currentOrgSlug = location.pathname.split('/')[2];
- const fetchedOrg = await api.requestPromise(`/organizations/${currentOrgSlug}/`, {
- query: {detailed: 0},
- });
-
- return hasNewReleases(fetchedOrg.features.includes('releases-v2'));
- } catch {
- return hasNewReleases(false);
- }
+ return hasNewReleases(true);
};
export const roundDuration = (seconds: number) => {
diff --git a/src/sentry/static/sentry/app/views/releasesV2/utils/switchReleasesButton.tsx b/src/sentry/static/sentry/app/views/releasesV2/utils/switchReleasesButton.tsx
index a32a058cfd403e..40791abb8b60bc 100644
--- a/src/sentry/static/sentry/app/views/releasesV2/utils/switchReleasesButton.tsx
+++ b/src/sentry/static/sentry/app/views/releasesV2/utils/switchReleasesButton.tsx
@@ -1,41 +1,11 @@
-import React from 'react';
-
-import {t} from 'app/locale';
-import Button from 'app/components/button';
-import {IconReleases} from 'app/icons';
-
-import {switchReleasesVersion} from './index';
-
type Props = {
orgId: string; // actual id, not slug
version: '1' | '2';
};
-const SwitchReleasesButton = ({orgId, version}: Props) => {
- const switchReleases = () => {
- switchReleasesVersion(version, orgId);
- };
-
- if (version === '2') {
- return (
- <Button
- priority="primary"
- size="small"
- icon={<IconReleases size="sm" />}
- onClick={switchReleases}
- >
- {t('Go to New Releases')}
- </Button>
- );
- }
-
- return (
- <div>
- <Button priority="link" size="small" onClick={switchReleases}>
- {t('Go to Legacy Releases')}
- </Button>
- </div>
- );
+const SwitchReleasesButton = (_props: Props) => {
+ // we are forcing everyone to version 2 now, we will delete the codebase behind v1 in a week or so
+ return null;
};
export default SwitchReleasesButton;
|
8162f488a1b30fb8d7f50635f655fe7e85399a01
|
2021-10-08 03:15:23
|
Colleen O'Rourke
|
ref(Slack): Allow users to enter a channel ID for alert rules on the front end (#29125)
| false
|
Allow users to enter a channel ID for alert rules on the front end (#29125)
|
ref
|
diff --git a/src/sentry/api/serializers/models/alert_rule_trigger_action.py b/src/sentry/api/serializers/models/alert_rule_trigger_action.py
index 0f5a0b746204b5..dd82d543b04146 100644
--- a/src/sentry/api/serializers/models/alert_rule_trigger_action.py
+++ b/src/sentry/api/serializers/models/alert_rule_trigger_action.py
@@ -28,6 +28,7 @@ def get_identifier_from_action(self, action):
]:
return int(action.target_identifier)
+ # if an input_channel_id is provided, we flip these to display properly
return (
action.target_display if action.target_display is not None else action.target_identifier
)
@@ -45,6 +46,7 @@ def serialize(self, obj, attrs, user):
AlertRuleTriggerAction.TargetType(obj.target_type)
],
"targetIdentifier": self.get_identifier_from_action(obj),
+ "inputChannelId": obj.target_identifier,
"integrationId": obj.integration_id,
"sentryAppId": obj.sentry_app_id,
"dateCreated": obj.date_added,
diff --git a/src/sentry/integrations/slack/notify_action.py b/src/sentry/integrations/slack/notify_action.py
index 7141ce37fb9877..ca3e31aa6ae951 100644
--- a/src/sentry/integrations/slack/notify_action.py
+++ b/src/sentry/integrations/slack/notify_action.py
@@ -31,7 +31,7 @@
class SlackNotifyServiceForm(forms.Form): # type: ignore
workspace = forms.ChoiceField(choices=(), widget=forms.Select())
channel = forms.CharField(widget=forms.TextInput())
- channel_id = forms.HiddenInput()
+ channel_id = forms.CharField(required=False, widget=forms.TextInput())
tags = forms.CharField(required=False, widget=forms.TextInput())
def __init__(self, *args: Any, **kwargs: Any) -> None:
@@ -147,7 +147,7 @@ def clean(self) -> Mapping[str, Any]:
class SlackNotifyServiceAction(IntegrationEventAction): # type: ignore
form_cls = SlackNotifyServiceForm
- label = "Send a notification to the {workspace} Slack workspace to {channel} and show tags {tags} in notification"
+ label = "Send a notification to the {workspace} Slack workspace to {channel} (optionally, an ID: {channel_id}) and show tags {tags} in notification"
prompt = "Send a Slack notification"
provider = "slack"
integration_key = "workspace"
@@ -160,6 +160,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:
"choices": [(i.id, i.name) for i in self.get_integrations()],
},
"channel": {"type": "string", "placeholder": "i.e #critical"},
+ "channel_id": {"type": "string", "placeholder": "i.e. CA2FRA079 or UA1J9RTE1"},
"tags": {"type": "string", "placeholder": "i.e environment,user,my_tag"},
}
@@ -209,6 +210,7 @@ def render_label(self) -> str:
return self.label.format(
workspace=self.get_integration_name(),
channel=self.get_option("channel"),
+ channel_id=self.get_option("channel_id"),
tags="[{}]".format(", ".join(tags)),
)
diff --git a/static/app/views/alerts/incidentRules/triggers/actionsPanel/actionSpecificTargetSelector.tsx b/static/app/views/alerts/incidentRules/triggers/actionsPanel/actionSpecificTargetSelector.tsx
new file mode 100644
index 00000000000000..5590a3081d8fc6
--- /dev/null
+++ b/static/app/views/alerts/incidentRules/triggers/actionsPanel/actionSpecificTargetSelector.tsx
@@ -0,0 +1,34 @@
+import {t} from 'app/locale';
+import {Action, ActionType, TargetType} from 'app/views/alerts/incidentRules/types';
+import Input from 'app/views/settings/components/forms/controls/input';
+
+type Props = {
+ action: Action;
+ disabled: boolean;
+ onChange: (value: string) => void;
+};
+
+function ActionSpecificTargetSelector({action, disabled, onChange}: Props) {
+ const handleChangeSpecificTargetIdentifier = (
+ e: React.ChangeEvent<HTMLInputElement>
+ ) => {
+ onChange(e.target.value);
+ };
+
+ if (action.targetType !== TargetType.SPECIFIC || action.type !== ActionType.SLACK) {
+ return null;
+ }
+ return (
+ <Input
+ type="text"
+ autoComplete="off"
+ disabled={disabled}
+ key="inputChannelId"
+ value={action.inputChannelId || ''}
+ onChange={handleChangeSpecificTargetIdentifier}
+ placeholder={t('optional: channel ID or user ID')}
+ />
+ );
+}
+
+export default ActionSpecificTargetSelector;
diff --git a/static/app/views/alerts/incidentRules/triggers/actionsPanel/index.tsx b/static/app/views/alerts/incidentRules/triggers/actionsPanel/index.tsx
index 4149449e3a3af0..5cafa9dd821d70 100644
--- a/static/app/views/alerts/incidentRules/triggers/actionsPanel/index.tsx
+++ b/static/app/views/alerts/incidentRules/triggers/actionsPanel/index.tsx
@@ -16,6 +16,7 @@ import {uniqueId} from 'app/utils/guid';
import {removeAtArrayIndex} from 'app/utils/removeAtArrayIndex';
import {replaceAtArrayIndex} from 'app/utils/replaceAtArrayIndex';
import withOrganization from 'app/utils/withOrganization';
+import ActionSpecificTargetSelector from 'app/views/alerts/incidentRules/triggers/actionsPanel/actionSpecificTargetSelector';
import ActionTargetSelector from 'app/views/alerts/incidentRules/triggers/actionsPanel/actionTargetSelector';
import DeleteActionButton from 'app/views/alerts/incidentRules/triggers/actionsPanel/deleteActionButton';
import {
@@ -59,6 +60,7 @@ const getCleanAction = (actionConfig, dateCreated?: string): Action => {
? actionConfig.allowedTargetTypes[0]
: null,
targetIdentifier: actionConfig.sentryAppId || '',
+ inputChannelId: null,
integrationId: actionConfig.integrationId,
sentryAppId: actionConfig.sentryAppId,
options: actionConfig.options || null,
@@ -117,12 +119,17 @@ const getFullActionTitle = ({
* Lists saved actions as well as control to add a new action
*/
class ActionsPanel extends PureComponent<Props> {
- handleChangeTargetIdentifier(triggerIndex: number, index: number, value: string) {
+ handleChangeKey(
+ triggerIndex: number,
+ index: number,
+ key: 'targetIdentifier' | 'inputChannelId',
+ value: string
+ ) {
const {triggers, onChange} = this.props;
const {actions} = triggers[triggerIndex];
const newAction = {
...actions[index],
- targetIdentifier: value,
+ [key]: value,
};
onChange(triggerIndex, triggers, replaceAtArrayIndex(actions, index, newAction));
@@ -313,14 +320,25 @@ class ActionsPanel extends PureComponent<Props> {
availableAction={availableAction}
disabled={disabled}
loading={loading}
- onChange={this.handleChangeTargetIdentifier.bind(
+ onChange={this.handleChangeKey.bind(
this,
triggerIndex,
- actionIdx
+ actionIdx,
+ 'targetIdentifier'
)}
organization={organization}
project={project}
/>
+ <ActionSpecificTargetSelector
+ action={action}
+ disabled={disabled}
+ onChange={this.handleChangeKey.bind(
+ this,
+ triggerIndex,
+ actionIdx,
+ 'inputChannelId'
+ )}
+ />
</PanelItemSelects>
<DeleteActionButton
triggerIndex={triggerIndex}
diff --git a/static/app/views/alerts/incidentRules/types.tsx b/static/app/views/alerts/incidentRules/types.tsx
index 4a21a133eedbf4..0d8e3f7f68c170 100644
--- a/static/app/views/alerts/incidentRules/types.tsx
+++ b/static/app/views/alerts/incidentRules/types.tsx
@@ -238,7 +238,10 @@ type UnsavedAction = {
* user_id, team_id, SentryApp id, etc
*/
targetIdentifier: string | null;
-
+ /**
+ * An optional Slack channel or user id the user can input to avoid rate limiting issues.
+ */
+ inputChannelId: string | null;
/**
* The id of the integration, can be null (e.g. email) or undefined (server errors when posting w/ null value)
*/
diff --git a/static/app/views/alerts/issueRuleEditor/ruleNode.tsx b/static/app/views/alerts/issueRuleEditor/ruleNode.tsx
index 8ae08a5c8b764e..f755c7b614702b 100644
--- a/static/app/views/alerts/issueRuleEditor/ruleNode.tsx
+++ b/static/app/views/alerts/issueRuleEditor/ruleNode.tsx
@@ -276,6 +276,22 @@ class RuleNode extends React.Component<Props> {
</MarginlessAlert>
);
}
+ if (data.id === 'sentry.integrations.slack.notify_action.SlackNotifyServiceAction') {
+ return (
+ <MarginlessAlert type="warning">
+ {tct(
+ 'Having rate limiting problems? Enter a channel or user ID. Read more [rateLimiting].',
+ {
+ rateLimiting: (
+ <ExternalLink href="https://docs.sentry.io/product/integrations/notification-incidents/slack/#rate-limiting-error">
+ {t('here')}
+ </ExternalLink>
+ ),
+ }
+ )}
+ </MarginlessAlert>
+ );
+ }
/**
* Would prefer to check if data is of `IssueAlertRuleAction` type, however we can't do typechecking at runtime as
* user defined types are erased through transpilation.
diff --git a/tests/sentry/api/endpoints/test_project_rules.py b/tests/sentry/api/endpoints/test_project_rules.py
index dd76982cb6fec6..3f1bd6af1d2738 100644
--- a/tests/sentry/api/endpoints/test_project_rules.py
+++ b/tests/sentry/api/endpoints/test_project_rules.py
@@ -312,6 +312,7 @@ def test_kicks_off_slack_async_job(
"name": "Send a notification to the funinthesun Slack workspace to #team-team-team and show tags [] in notification",
"workspace": str(integration.id),
"channel": "#team-team-team",
+ "channel_id": "",
"tags": "",
}
],
diff --git a/tests/sentry/integrations/slack/test_notify_action.py b/tests/sentry/integrations/slack/test_notify_action.py
index 5d67fad1b36ce0..50965f7f65c888 100644
--- a/tests/sentry/integrations/slack/test_notify_action.py
+++ b/tests/sentry/integrations/slack/test_notify_action.py
@@ -50,25 +50,35 @@ def test_no_upgrade_notice_bot_app(self):
def test_render_label(self):
rule = self.get_rule(
- data={"workspace": self.integration.id, "channel": "#my-channel", "tags": "one, two"}
+ data={
+ "workspace": self.integration.id,
+ "channel": "#my-channel",
+ "channel_id": "",
+ "tags": "one, two",
+ }
)
assert (
rule.render_label()
- == "Send a notification to the Awesome Team Slack workspace to #my-channel and show tags [one, two] in notification"
+ == "Send a notification to the Awesome Team Slack workspace to #my-channel (optionally, an ID: ) and show tags [one, two] in notification"
)
def test_render_label_without_integration(self):
self.integration.delete()
rule = self.get_rule(
- data={"workspace": self.integration.id, "channel": "#my-channel", "tags": ""}
+ data={
+ "workspace": self.integration.id,
+ "channel": "#my-channel",
+ "channel_id": "",
+ "tags": "",
+ }
)
label = rule.render_label()
assert (
label
- == "Send a notification to the [removed] Slack workspace to #my-channel and show tags [] in notification"
+ == "Send a notification to the [removed] Slack workspace to #my-channel (optionally, an ID: ) and show tags [] in notification"
)
@responses.activate
|
6a9c7e26b1059e515524b646678edab26ce1cba1
|
2018-03-14 06:43:15
|
David Cramer
|
fix: Correct missing team name for project list
| false
|
Correct missing team name for project list
|
fix
|
diff --git a/src/sentry/static/sentry/app/views/organizationDashboard.jsx b/src/sentry/static/sentry/app/views/organizationDashboard.jsx
index 13dfc5beb9b157..a2e9edffb16c66 100644
--- a/src/sentry/static/sentry/app/views/organizationDashboard.jsx
+++ b/src/sentry/static/sentry/app/views/organizationDashboard.jsx
@@ -166,7 +166,7 @@ const ProjectListOld = createReactClass({
let {maxProjects, projects} = this.props;
projects = sortArray(projects, item => {
- return [!item.isBookmarked, item.teamName, item.name];
+ return [!item.isBookmarked, item.team && item.team.name, item.name];
});
// project list is
@@ -209,7 +209,7 @@ const ProjectListOld = createReactClass({
)}
{project.name}
</h4>
- <h5>{project.teamName}</h5>
+ <h5>{project.team ? project.team.name : <span> </span>}</h5>
</Link>
</li>
);
|
5ccc45b0afad496ade2aa32b74e1f7dca3ef68fc
|
2022-10-19 16:40:28
|
Evan Purkhiser
|
test(js): Convert AwsLambdaCloudformation to RTL (#40252)
| false
|
Convert AwsLambdaCloudformation to RTL (#40252)
|
test
|
diff --git a/static/app/views/integrationPipeline/awsLambdaCloudformation.spec.jsx b/static/app/views/integrationPipeline/awsLambdaCloudformation.spec.jsx
index a45ac885cd63e7..49f80a582b6365 100644
--- a/static/app/views/integrationPipeline/awsLambdaCloudformation.spec.jsx
+++ b/static/app/views/integrationPipeline/awsLambdaCloudformation.spec.jsx
@@ -1,19 +1,21 @@
+import selectEvent from 'react-select-event';
import * as qs from 'query-string';
-import {mountWithTheme} from 'sentry-test/enzyme';
-import {selectByValue} from 'sentry-test/select-new';
+import {fireEvent, render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
import AwsLambdaCloudformation from 'sentry/views/integrationPipeline/awsLambdaCloudformation';
describe('AwsLambdaCloudformation', () => {
- let wrapper;
let windowAssignMock;
+
beforeEach(() => {
windowAssignMock = jest.fn();
window.location.assign = windowAssignMock;
window.localStorage.setItem('AWS_EXTERNAL_ID', 'my-id');
+ });
- wrapper = mountWithTheme(
+ it('submit arn', async () => {
+ render(
<AwsLambdaCloudformation
baseCloudformationUrl="https://console.aws.amazon.com/cloudformation/home#/stacks/create/review"
templateUrl="https://example.com/file.json"
@@ -24,23 +26,25 @@ describe('AwsLambdaCloudformation', () => {
initialStepNumber={0}
/>
);
- });
- it('submit arn', async () => {
- wrapper.find('button[name="showInputs"]').simulate('click');
- wrapper
- .find('input[name="accountNumber"]')
- .simulate('change', {target: {value: '599817902985'}});
+ // Open configuration fields
+ userEvent.click(screen.getByRole('button', {name: "I've created the stack"}));
- selectByValue(wrapper, 'us-west-1');
+ // XXX(epurkhiser): This form is pretty wonky with how it works, and
+ // probably needs cleaned up again in the future. I couldn't get
+ // userEvent.type to work here because of something relating to the
+ // validation I think.
- await tick();
+ // Fill out fields
+ const accountNumber = screen.getByRole('textbox', {name: 'AWS Account Number'});
+ fireEvent.change(accountNumber, {target: {value: '599817902985'}});
- wrapper.find('StyledButton[aria-label="Next"]').simulate('click');
+ await selectEvent.select(screen.getByRole('textbox', {name: 'AWS Region'}), [
+ ['us-west-1'],
+ ]);
- const {
- location: {origin},
- } = window;
+ expect(screen.getByRole('button', {name: 'Next'})).toBeEnabled();
+ userEvent.click(screen.getByRole('button', {name: 'Next'}));
const query = qs.stringify({
accountNumber: '599817902985',
@@ -49,7 +53,7 @@ describe('AwsLambdaCloudformation', () => {
});
expect(windowAssignMock).toHaveBeenCalledWith(
- `${origin}/extensions/aws_lambda/setup/?${query}`
+ `${window.location.origin}/extensions/aws_lambda/setup/?${query}`
);
});
});
|
ab1d94726fbc6deadc87e49a84fc9c79e685931f
|
2023-02-22 22:55:06
|
Colleen O'Rourke
|
ref(grouptype): Handle invalid issue.type search better (#44910)
| false
|
Handle invalid issue.type search better (#44910)
|
ref
|
diff --git a/src/sentry/issues/grouptype.py b/src/sentry/issues/grouptype.py
index f47ab9beac3a1d..276552be04e31f 100644
--- a/src/sentry/issues/grouptype.py
+++ b/src/sentry/issues/grouptype.py
@@ -3,7 +3,7 @@
from collections import defaultdict
from dataclasses import dataclass
from enum import Enum
-from typing import Any, Dict, Set, Type
+from typing import Any, Dict, Optional, Set, Type
class GroupCategory(Enum):
@@ -52,9 +52,9 @@ def get_group_types_by_category(category: int) -> Set[int]:
return _category_lookup[category]
-def get_group_type_by_slug(slug: str) -> Type[GroupType]:
+def get_group_type_by_slug(slug: str) -> Optional[Type[GroupType]]:
if slug not in _slug_lookup:
- raise ValueError(f"No group type with the slug {slug} is registered.")
+ return None
return _slug_lookup[slug]
diff --git a/tests/sentry/api/test_issue_search.py b/tests/sentry/api/test_issue_search.py
index afdd0c8821a289..0d6b5a7a0cea58 100644
--- a/tests/sentry/api/test_issue_search.py
+++ b/tests/sentry/api/test_issue_search.py
@@ -310,5 +310,5 @@ def test(self):
assert convert_type_value(
["error", "performance_n_plus_one_db_queries"], [self.project], self.user, None
) == [1, 1006]
- with pytest.raises(ValueError):
+ with pytest.raises(InvalidSearchQuery):
convert_type_value(["hellboy"], [self.project], self.user, None)
diff --git a/tests/sentry/issues/test_grouptype.py b/tests/sentry/issues/test_grouptype.py
index 699fd8549b54aa..472266d5421c4a 100644
--- a/tests/sentry/issues/test_grouptype.py
+++ b/tests/sentry/issues/test_grouptype.py
@@ -59,11 +59,7 @@ class TestGroupType(GroupType):
assert get_group_type_by_slug(TestGroupType.slug) == TestGroupType
- nonexistent_slug = "meow"
- with self.assertRaisesMessage(
- ValueError, f"No group type with the slug {nonexistent_slug} is registered."
- ):
- get_group_type_by_slug(nonexistent_slug)
+ assert get_group_type_by_slug("meow") is None
def test_category_validation(self) -> None:
with patch.dict(_group_type_registry, {}, clear=True):
diff --git a/tests/snuba/search/test_backend.py b/tests/snuba/search/test_backend.py
index 679e4b422b86c4..75b626d83eae92 100644
--- a/tests/snuba/search/test_backend.py
+++ b/tests/snuba/search/test_backend.py
@@ -470,7 +470,7 @@ def test_type(self):
)
assert set(results) == {self.group1, self.group2, group_3, group_4}
- with pytest.raises(ValueError):
+ with pytest.raises(InvalidSearchQuery):
self.make_query(search_filter_query="issue.type:performance_i_dont_exist")
def test_status_with_environment(self):
|
bfba93cac3da84076b60f3856cc92194824d78ed
|
2021-10-08 12:26:26
|
Evan Purkhiser
|
ref(js): useTheme in HelpSearchModal (#29178)
| false
|
useTheme in HelpSearchModal (#29178)
|
ref
|
diff --git a/static/app/components/modals/helpSearchModal.tsx b/static/app/components/modals/helpSearchModal.tsx
index ac01626c257b09..f192e02811bd41 100644
--- a/static/app/components/modals/helpSearchModal.tsx
+++ b/static/app/components/modals/helpSearchModal.tsx
@@ -1,4 +1,4 @@
-import {ClassNames, css, withTheme} from '@emotion/react';
+import {ClassNames, css, useTheme} from '@emotion/react';
import styled from '@emotion/styled';
import {ModalRenderProps} from 'app/actionCreators/modal';
@@ -7,30 +7,30 @@ import Hook from 'app/components/hook';
import {t} from 'app/locale';
import space from 'app/styles/space';
import {Organization} from 'app/types';
-import {Theme} from 'app/utils/theme';
import withOrganization from 'app/utils/withOrganization';
type Props = ModalRenderProps & {
- theme: Theme;
organization: Organization;
placeholder?: string;
};
-const HelpSearchModal = ({
+function HelpSearchModal({
Body,
closeModal,
- theme,
organization,
placeholder = t('Search for documentation, FAQs, blog posts...'),
...props
-}: Props) => (
- <Body>
- <ClassNames>
- {({css: injectedCss}) => (
- <HelpSearch
- {...props}
- entryPoint="sidebar_help"
- dropdownStyle={injectedCss`
+}: Props) {
+ const theme = useTheme();
+
+ return (
+ <Body>
+ <ClassNames>
+ {({css: injectedCss}) => (
+ <HelpSearch
+ {...props}
+ entryPoint="sidebar_help"
+ dropdownStyle={injectedCss`
width: 100%;
border: transparent;
border-top-left-radius: 0;
@@ -39,20 +39,23 @@ const HelpSearchModal = ({
box-shadow: none;
border-top: 1px solid ${theme.border};
`}
- renderInput={({getInputProps}) => (
- <InputWrapper>
- <Input
- autoFocus
- {...getInputProps({type: 'text', label: placeholder, placeholder})}
- />
- </InputWrapper>
- )}
- resultFooter={<Hook name="help-modal:footer" {...{organization, closeModal}} />}
- />
- )}
- </ClassNames>
- </Body>
-);
+ renderInput={({getInputProps}) => (
+ <InputWrapper>
+ <Input
+ autoFocus
+ {...getInputProps({type: 'text', label: placeholder, placeholder})}
+ />
+ </InputWrapper>
+ )}
+ resultFooter={
+ <Hook name="help-modal:footer" {...{organization, closeModal}} />
+ }
+ />
+ )}
+ </ClassNames>
+ </Body>
+ );
+}
const InputWrapper = styled('div')`
padding: ${space(0.25)};
@@ -76,4 +79,4 @@ export const modalCss = css`
}
`;
-export default withTheme(withOrganization(HelpSearchModal));
+export default withOrganization(HelpSearchModal);
|
1dd34767bef788dd61eb08daf9047877cc187bcf
|
2023-07-18 02:24:18
|
Richard Ortenberg
|
feat(crons): Use timeout_at for timed out check-ins (#52570)
| false
|
Use timeout_at for timed out check-ins (#52570)
|
feat
|
diff --git a/src/sentry/monitors/tasks.py b/src/sentry/monitors/tasks.py
index 49972e3923baf4..749d78052c4a81 100644
--- a/src/sentry/monitors/tasks.py
+++ b/src/sentry/monitors/tasks.py
@@ -1,5 +1,4 @@
import logging
-from datetime import timedelta
from django.utils import timezone
@@ -102,21 +101,13 @@ def check_monitors(current_datetime=None):
except Exception:
logger.exception("Exception in check_monitors - mark missed")
- qs = MonitorCheckIn.objects.filter(status=CheckInStatus.IN_PROGRESS).select_related(
- "monitor", "monitor_environment"
- )[:CHECKINS_LIMIT]
+ qs = MonitorCheckIn.objects.filter(
+ status=CheckInStatus.IN_PROGRESS, timeout_at__lte=current_datetime
+ ).select_related("monitor", "monitor_environment")[:CHECKINS_LIMIT]
metrics.gauge("sentry.monitors.tasks.check_monitors.timeout_count", qs.count())
# check for any monitors which are still running and have exceeded their maximum runtime
for checkin in qs:
try:
- timeout = timedelta(
- minutes=(checkin.monitor.config or {}).get("max_runtime") or TIMEOUT
- )
- # Check against date_updated to allow monitors to run for longer as
- # long as they continue to send heart beats updating the checkin
- if checkin.date_updated > current_datetime - timeout:
- continue
-
monitor_environment = checkin.monitor_environment
logger.info(
"monitor_environment.checkin-timeout",
@@ -136,7 +127,16 @@ def check_monitors(current_datetime=None):
if not has_newer_result:
monitor_environment.mark_failed(
reason=MonitorFailure.DURATION,
- occurrence_context={"duration": (timeout.seconds // 60) % 60},
+ occurrence_context={
+ "duration": (checkin.monitor.config or {}).get("max_runtime") or TIMEOUT
+ },
)
except Exception:
logger.exception("Exception in check_monitors - mark timeout")
+
+ # safety check for check-ins stuck in the backlog
+ backlog_count = MonitorCheckIn.objects.filter(
+ status=CheckInStatus.IN_PROGRESS, timeout_at__isnull=True
+ ).count()
+ if backlog_count:
+ logger.exception(f"Exception in check_monitors - backlog count {backlog_count} is > 0")
diff --git a/tests/sentry/monitors/test_tasks.py b/tests/sentry/monitors/test_tasks.py
index 35fe8923463190..f5ef5113610135 100644
--- a/tests/sentry/monitors/test_tasks.py
+++ b/tests/sentry/monitors/test_tasks.py
@@ -206,6 +206,7 @@ def test_timeout_with_no_future_complete_checkin(self):
status=CheckInStatus.IN_PROGRESS,
date_added=check_in_24hr_ago,
date_updated=check_in_24hr_ago,
+ timeout_at=check_in_24hr_ago + timedelta(minutes=30),
)
# We started another checkin right now
checkin2 = MonitorCheckIn.objects.create(
@@ -215,6 +216,7 @@ def test_timeout_with_no_future_complete_checkin(self):
status=CheckInStatus.IN_PROGRESS,
date_added=next_checkin_ts,
date_updated=next_checkin_ts,
+ timeout_at=next_checkin_ts + timedelta(minutes=30),
)
assert checkin1.date_added == checkin1.date_updated == check_in_24hr_ago
@@ -268,6 +270,7 @@ def test_timeout_with_future_complete_checkin(self):
status=CheckInStatus.IN_PROGRESS,
date_added=check_in_24hr_ago,
date_updated=check_in_24hr_ago,
+ timeout_at=check_in_24hr_ago + timedelta(minutes=30),
)
checkin2 = MonitorCheckIn.objects.create(
monitor=monitor,
@@ -276,6 +279,7 @@ def test_timeout_with_future_complete_checkin(self):
status=CheckInStatus.OK,
date_added=next_checkin_ts,
date_updated=next_checkin_ts,
+ timeout_at=next_checkin_ts + timedelta(minutes=30),
)
assert checkin1.date_added == checkin1.date_updated == check_in_24hr_ago
@@ -321,6 +325,7 @@ def test_timeout_via_max_runtime_configuration(self):
status=CheckInStatus.IN_PROGRESS,
date_added=next_checkin_ts,
date_updated=next_checkin_ts,
+ timeout_at=next_checkin_ts + timedelta(minutes=60),
)
assert checkin.date_added == checkin.date_updated == next_checkin_ts
@@ -424,6 +429,7 @@ def test_timeout_exception_handling(self, logger):
status=CheckInStatus.IN_PROGRESS,
date_added=check_in_24hr_ago,
date_updated=check_in_24hr_ago,
+ timeout_at=check_in_24hr_ago + timedelta(minutes=30),
)
# This monitor will be fine
@@ -448,6 +454,7 @@ def test_timeout_exception_handling(self, logger):
status=CheckInStatus.IN_PROGRESS,
date_added=check_in_24hr_ago,
date_updated=check_in_24hr_ago,
+ timeout_at=check_in_24hr_ago + timedelta(minutes=30),
)
checkin2 = MonitorCheckIn.objects.create(
monitor=monitor,
@@ -456,6 +463,7 @@ def test_timeout_exception_handling(self, logger):
status=CheckInStatus.IN_PROGRESS,
date_added=next_checkin_ts,
date_updated=next_checkin_ts,
+ timeout_at=next_checkin_ts + timedelta(minutes=30),
)
assert checkin1.date_added == checkin1.date_updated == check_in_24hr_ago
|
da908f8024891b74cd07ae16ad00bbdd5c4147a5
|
2024-02-22 20:25:16
|
Dominik Buszowiecki
|
feat(browser-starfish): add use case for bundle analysis (#65267)
| false
|
add use case for bundle analysis (#65267)
|
feat
|
diff --git a/src/sentry/sentry_metrics/indexer/strings.py b/src/sentry/sentry_metrics/indexer/strings.py
index 14e06aa0ec570c..53c3a0dacda3ac 100644
--- a/src/sentry/sentry_metrics/indexer/strings.py
+++ b/src/sentry/sentry_metrics/indexer/strings.py
@@ -224,11 +224,17 @@
"c:escalating_issues/event_ingested@none": PREFIX + 500,
}
-# 600-999
+# 600-699
PROFILING_METRIC_NAMES = {
"d:profiles/function.duration@millisecond": PREFIX + 600,
}
+# 700-799
+BUNDLE_ANALYSIS_METRIC_NAMES = {
+ "d:bundle_analysis/bundle_size@byte": PREFIX + 700,
+}
+
+
SHARED_STRINGS = {
**SESSION_METRIC_NAMES,
**TRANSACTION_METRICS_NAMES,
@@ -236,6 +242,7 @@
**ESCALATING_ISSUES_METRIC_NAMES,
**PROFILING_METRIC_NAMES,
**SHARED_TAG_STRINGS,
+ **BUNDLE_ANALYSIS_METRIC_NAMES,
}
REVERSE_SHARED_STRINGS = {v: k for k, v in SHARED_STRINGS.items()}
diff --git a/src/sentry/sentry_metrics/use_case_id_registry.py b/src/sentry/sentry_metrics/use_case_id_registry.py
index 660b530c289d7c..a4baf24dd248df 100644
--- a/src/sentry/sentry_metrics/use_case_id_registry.py
+++ b/src/sentry/sentry_metrics/use_case_id_registry.py
@@ -18,6 +18,7 @@ class UseCaseID(Enum):
ESCALATING_ISSUES = "escalating_issues"
CUSTOM = "custom"
PROFILES = "profiles"
+ BUNDLE_ANALYSIS = "bundle_analysis"
# UseCaseKey will be renamed to MetricPathKey
@@ -27,6 +28,7 @@ class UseCaseID(Enum):
UseCaseID.SESSIONS: UseCaseKey.RELEASE_HEALTH,
UseCaseID.ESCALATING_ISSUES: UseCaseKey.PERFORMANCE,
UseCaseID.CUSTOM: UseCaseKey.PERFORMANCE,
+ UseCaseID.BUNDLE_ANALYSIS: UseCaseKey.PERFORMANCE,
UseCaseID.PROFILES: UseCaseKey.PERFORMANCE,
}
diff --git a/src/sentry/snuba/metrics/fields/base.py b/src/sentry/snuba/metrics/fields/base.py
index ad6553d98ea803..c2d7024f16431c 100644
--- a/src/sentry/snuba/metrics/fields/base.py
+++ b/src/sentry/snuba/metrics/fields/base.py
@@ -216,6 +216,8 @@ def _get_entity_of_metric_mri(
)
elif use_case_id is UseCaseID.ESCALATING_ISSUES:
entity_keys_set = frozenset({EntityKey.GenericMetricsCounters})
+ elif use_case_id is UseCaseID.BUNDLE_ANALYSIS:
+ entity_keys_set = frozenset({EntityKey.GenericMetricsDistributions})
elif use_case_id is UseCaseID.CUSTOM:
entity_keys_set = frozenset(
{
@@ -448,6 +450,7 @@ def generate_snql_function(
UseCaseID.SPANS,
UseCaseID.CUSTOM,
UseCaseID.ESCALATING_ISSUES,
+ UseCaseID.BUNDLE_ANALYSIS,
]:
snuba_function = GENERIC_OP_TO_SNUBA_FUNCTION[entity][self.op]
else:
@@ -1295,8 +1298,10 @@ def run_post_query_function(
compute_func_args = []
for constituent in self.metrics:
key = f"{constituent}{COMPOSITE_ENTITY_CONSTITUENT_ALIAS}{alias}"
- compute_func_args.append(data[key]) if idx is None else compute_func_args.append(
- data[key][idx]
+ (
+ compute_func_args.append(data[key])
+ if idx is None
+ else compute_func_args.append(data[key][idx])
)
# ToDo(ahmed): This won't work if there is not post_query_func because there is an assumption that this function
# will aggregate the result somehow
diff --git a/src/sentry/snuba/metrics/naming_layer/mri.py b/src/sentry/snuba/metrics/naming_layer/mri.py
index 33f40a35322e78..1138020915c42c 100644
--- a/src/sentry/snuba/metrics/naming_layer/mri.py
+++ b/src/sentry/snuba/metrics/naming_layer/mri.py
@@ -16,6 +16,7 @@
`SessionMetricKey` with the same name i.e. `SessionMetricKey.CRASH_FREE_RATE` and hence is a public
metric that is queryable by the API.
"""
+
__all__ = (
"SessionMRI",
"TransactionMRI",
@@ -23,6 +24,7 @@
"MRI_SCHEMA_REGEX",
"MRI_EXPRESSION_REGEX",
"ErrorsMRI",
+ "BundleAnalysisMRI",
"parse_mri",
"get_available_operations",
"is_mri_field",
@@ -195,6 +197,10 @@ class ErrorsMRI(Enum):
EVENT_INGESTED = "c:escalating_issues/event_ingested@none"
+class BundleAnalysisMRI(Enum):
+ BUNDLE_SIZE = "d:bundle_analysis/bundle_size@byte"
+
+
@dataclass
class ParsedMRI:
entity: str
|
3dfba821432ab23f7ed1dc0b52b88d69c3168eef
|
2023-02-16 05:52:38
|
Evan Purkhiser
|
ref(crons): Subsort by last checkin (#44703)
| false
|
Subsort by last checkin (#44703)
|
ref
|
diff --git a/src/sentry/api/endpoints/organization_monitors.py b/src/sentry/api/endpoints/organization_monitors.py
index 82d40d9d2662b7..eb49a57a3ddc38 100644
--- a/src/sentry/api/endpoints/organization_monitors.py
+++ b/src/sentry/api/endpoints/organization_monitors.py
@@ -97,7 +97,7 @@ def get(self, request: Request, organization) -> Response:
return self.paginate(
request=request,
queryset=queryset,
- order_by=("status_order", "-name"),
+ order_by=("status_order", "-last_checkin"),
on_results=lambda x: serialize(x, request.user),
paginator_cls=OffsetPaginator,
)
diff --git a/tests/sentry/api/endpoints/test_organization_monitors.py b/tests/sentry/api/endpoints/test_organization_monitors.py
index 5b713d434fd62a..433782682a191e 100644
--- a/tests/sentry/api/endpoints/test_organization_monitors.py
+++ b/tests/sentry/api/endpoints/test_organization_monitors.py
@@ -1,3 +1,6 @@
+from __future__ import annotations
+
+from datetime import datetime, timedelta
from unittest.mock import patch
from sentry.models import Monitor, MonitorStatus, MonitorType, ScheduleType
@@ -30,17 +33,23 @@ def test_simple(self):
self.check_valid_response(response, [monitor])
def test_sort(self):
- def add_status_monitor(status_key: str):
+ last_checkin = datetime.now() - timedelta(minutes=1)
+ last_checkin_older = datetime.now() - timedelta(minutes=5)
+
+ def add_status_monitor(status_key: str, date: datetime | None = None):
return Monitor.objects.create(
project_id=self.project.id,
organization_id=self.organization.id,
status=getattr(MonitorStatus, status_key),
+ last_checkin=date or last_checkin,
name=status_key,
)
+ # Subsort next checkin time
monitor_active = add_status_monitor("ACTIVE")
monitor_ok = add_status_monitor("OK")
monitor_disabled = add_status_monitor("DISABLED")
+ monitor_error_older_checkin = add_status_monitor("ERROR", last_checkin_older)
monitor_error = add_status_monitor("ERROR")
monitor_missed_checkin = add_status_monitor("MISSED_CHECKIN")
@@ -49,6 +58,7 @@ def add_status_monitor(status_key: str):
response,
[
monitor_error,
+ monitor_error_older_checkin,
monitor_missed_checkin,
monitor_ok,
monitor_active,
|
cf021045cb730aca1ca9a1a85326214146e81f4b
|
2020-11-17 07:46:08
|
Evan Purkhiser
|
chore(ts): Convert adminQueue (#21975)
| false
|
Convert adminQueue (#21975)
|
chore
|
diff --git a/src/sentry/static/sentry/app/views/admin/adminQueue.jsx b/src/sentry/static/sentry/app/views/admin/adminQueue.tsx
similarity index 84%
rename from src/sentry/static/sentry/app/views/admin/adminQueue.jsx
rename to src/sentry/static/sentry/app/views/admin/adminQueue.tsx
index c940ae4c5fb7c5..2d22c005907bea 100644
--- a/src/sentry/static/sentry/app/views/admin/adminQueue.jsx
+++ b/src/sentry/static/sentry/app/views/admin/adminQueue.tsx
@@ -5,7 +5,20 @@ import {Panel, PanelHeader, PanelBody} from 'app/components/panels';
import InternalStatChart from 'app/components/internalStatChart';
import {SelectField} from 'app/components/forms';
-export default class AdminQueue extends AsyncView {
+const TIME_WINDOWS = ['1h', '1d', '1w'] as const;
+
+type TimeWindow = typeof TIME_WINDOWS[number];
+
+type State = AsyncView['state'] & {
+ timeWindow: TimeWindow;
+ since: number;
+ resolution: string;
+ taskName: string;
+ activeTask: string;
+ taskList: string[];
+};
+
+export default class AdminQueue extends AsyncView<{}, State> {
getDefaultState() {
return {
...super.getDefaultState(),
@@ -16,12 +29,12 @@ export default class AdminQueue extends AsyncView {
};
}
- getEndpoints() {
+ getEndpoints(): [string, string][] {
return [['taskList', '/internal/queue/tasks/']];
}
- changeWindow(timeWindow) {
- let seconds;
+ changeWindow(timeWindow: TimeWindow) {
+ let seconds: number;
if (timeWindow === '1h') {
seconds = 3600;
} else if (timeWindow === '1d') {
@@ -37,9 +50,9 @@ export default class AdminQueue extends AsyncView {
});
}
- changeTask = value => {
+ changeTask(value: string) {
this.setState({activeTask: value});
- };
+ }
renderBody() {
const {activeTask, taskList} = this.state;
@@ -47,7 +60,7 @@ export default class AdminQueue extends AsyncView {
return (
<div>
<div className="btn-group pull-right">
- {['1h', '1d', '1w'].map(r => (
+ {TIME_WINDOWS.map(r => (
<a
className={`btn btn-sm ${
r === this.state.timeWindow ? 'btn-primary' : 'btn-default'
@@ -82,9 +95,9 @@ export default class AdminQueue extends AsyncView {
<SelectField
deprecatedSelectControl
name="task"
- onChange={this.changeTask}
+ onChange={value => this.changeTask(value as string)}
value={activeTask}
- allowClear
+ clearable
choices={[''].concat(...taskList).map(t => [t, t])}
/>
</div>
|
c90241c96c34055a9ab7366994ed740e101a0a74
|
2024-03-01 03:53:38
|
Leander Rodrigues
|
ref(assignment): Use internal feature handler rather than settings (#66104)
| false
|
Use internal feature handler rather than settings (#66104)
|
ref
|
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py
index ae8f50b8d8bfda..262e57e23d18e8 100644
--- a/src/sentry/conf/server.py
+++ b/src/sentry/conf/server.py
@@ -1582,6 +1582,8 @@ def custom_parameter_sort(parameter: dict) -> tuple[str, int]:
"organizations:higher-ownership-limit": False,
# Enable incidents feature
"organizations:incidents": False,
+ # Enable increased issue_owners rate limit for auto-assignment
+ "organizations:increased-issue-owners-rate-limit": False,
# Enable integration functionality to work with alert rules
"organizations:integrations-alert-rule": True,
# Enable integration functionality to work with alert rules (specifically chat integrations)
@@ -3789,10 +3791,6 @@ def build_cdc_postgres_init_db_volume(settings: Any) -> dict[str, dict[str, str]
"path": "sentry.utils.locking.backends.redis.RedisLockBackend",
"options": {"cluster": "default"},
}
-SENTRY_POST_PROCESS_CONFIGURATION: Mapping[str, Any] = {
- "org_ids_with_increased_issue_owners_ratelimit": set()
-}
-
# maximum number of projects allowed to query snuba with for the organization_vitals_overview endpoint
ORGANIZATION_VITALS_OVERVIEW_PROJECT_LIMIT = 300
diff --git a/src/sentry/features/__init__.py b/src/sentry/features/__init__.py
index 65fc720a3ed1a0..dcefb8f18ed385 100644
--- a/src/sentry/features/__init__.py
+++ b/src/sentry/features/__init__.py
@@ -111,6 +111,7 @@
default_manager.add("organizations:grouping-title-ui", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
default_manager.add("organizations:grouping-tree-ui", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
default_manager.add("organizations:higher-ownership-limit", OrganizationFeature, FeatureHandlerStrategy.INTERNAL)
+default_manager.add("organizations:increased-issue-owners-rate-limit", OrganizationFeature, FeatureHandlerStrategy.INTERNAL)
default_manager.add("organizations:integrations-deployment", OrganizationFeature, FeatureHandlerStrategy.INTERNAL)
default_manager.add("organizations:integrations-feature-flag-integration", OrganizationFeature, FeatureHandlerStrategy.INTERNAL)
default_manager.add("organizations:integrations-gh-invite", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
diff --git a/src/sentry/tasks/post_process.py b/src/sentry/tasks/post_process.py
index fb0ffc8f0755b6..e559d929f2e33d 100644
--- a/src/sentry/tasks/post_process.py
+++ b/src/sentry/tasks/post_process.py
@@ -5,7 +5,7 @@
from collections.abc import Mapping, Sequence
from datetime import datetime, timedelta
from time import time
-from typing import TYPE_CHECKING, Any, TypedDict
+from typing import TYPE_CHECKING, TypedDict
import sentry_sdk
from django.conf import settings
@@ -50,7 +50,6 @@
locks = LockManager(build_instance_from_options(settings.SENTRY_POST_PROCESS_LOCKS_BACKEND_OPTIONS))
-configuration: Mapping[str, Any] = settings.SENTRY_POST_PROCESS_CONFIGURATION
ISSUE_OWNERS_PER_PROJECT_PER_MIN_RATELIMIT = 50
HIGHER_ISSUE_OWNERS_PER_PROJECT_PER_MIN_RATELIMIT = 200
@@ -175,12 +174,13 @@ def _capture_group_stats(job: PostProcessJob) -> None:
def should_issue_owners_ratelimit(project_id: int, group_id: int, organization_id: int | None):
"""
- Make sure that we do not accept more groups than ISSUE_OWNERS_PER_PROJECT_PER_MIN_RATELIMIT at the project level.
+ Make sure that we do not accept more groups than the enforced_limit at the project level.
"""
+ from sentry.models.organization import Organization
+
enforced_limit = ISSUE_OWNERS_PER_PROJECT_PER_MIN_RATELIMIT
- if organization_id and organization_id in configuration.get(
- "org_ids_with_increased_issue_owners_ratelimit", set()
- ):
+ organization = Organization.objects.get_from_cache(id=organization_id)
+ if features.has("organizations:increased-issue-owners-rate-limit", organization=organization):
enforced_limit = HIGHER_ISSUE_OWNERS_PER_PROJECT_PER_MIN_RATELIMIT
cache_key = f"issue_owner_assignment_ratelimiter:{project_id}"
diff --git a/tests/sentry/tasks/test_post_process.py b/tests/sentry/tasks/test_post_process.py
index b595f88a733082..9c22c43614aad3 100644
--- a/tests/sentry/tasks/test_post_process.py
+++ b/tests/sentry/tasks/test_post_process.py
@@ -1354,10 +1354,7 @@ def test_issue_owners_should_ratelimit(self, mock_logger):
mock_logger.reset_mock()
# Raise this organization's ratelimit
- mock_config = {
- "org_ids_with_increased_issue_owners_ratelimit": {self.project.organization_id}
- }
- with patch.dict("sentry.tasks.post_process.configuration", mock_config):
+ with self.feature("organizations:increased-issue-owners-rate-limit"):
self.call_post_process_group(
is_new=False,
is_regression=False,
@@ -1378,10 +1375,7 @@ def test_issue_owners_should_ratelimit(self, mock_logger):
datetime.now(),
),
)
- mock_config = {
- "org_ids_with_increased_issue_owners_ratelimit": {self.project.organization_id}
- }
- with patch.dict("sentry.tasks.post_process.configuration", mock_config):
+ with self.feature("organizations:increased-issue-owners-rate-limit"):
self.call_post_process_group(
is_new=False,
is_regression=False,
|
6dc7b1475eaf684ec21eb7cd0333b35d154f893c
|
2019-01-03 01:29:59
|
Lyn Nagara
|
fix(ui): Fix broken snapshot (#11317)
| false
|
Fix broken snapshot (#11317)
|
fix
|
diff --git a/tests/js/spec/views/userFeedback/__snapshots__/organizationUserFeedback.spec.jsx.snap b/tests/js/spec/views/userFeedback/__snapshots__/organizationUserFeedback.spec.jsx.snap
index 7edde0590135a3..7a5437058bc85e 100644
--- a/tests/js/spec/views/userFeedback/__snapshots__/organizationUserFeedback.spec.jsx.snap
+++ b/tests/js/spec/views/userFeedback/__snapshots__/organizationUserFeedback.spec.jsx.snap
@@ -447,10 +447,10 @@ exports[`OrganizationUserFeedback renders 1`] = `
>
<Header>
<Base
- className="css-1xc47v8-Header e10yv9i90"
+ className="css-1651jh1-Header e10yv9i90"
>
<div
- className="css-1xc47v8-Header e10yv9i90"
+ className="css-1651jh1-Header e10yv9i90"
is={null}
>
<HeaderItemPosition>
|
84fec2560b93040b2fc0997da3abb770e6dca557
|
2024-05-17 01:06:48
|
George Gritsouk
|
feat(insights): Insights backend route (#71038)
| false
|
Insights backend route (#71038)
|
feat
|
diff --git a/src/sentry/web/urls.py b/src/sentry/web/urls.py
index fde08d4ad3a53c..6282e0a0aff566 100644
--- a/src/sentry/web/urls.py
+++ b/src/sentry/web/urls.py
@@ -719,6 +719,12 @@
react_page_view,
name="performance",
),
+ # Insights
+ re_path(
+ r"^insights/",
+ react_page_view,
+ name="insights",
+ ),
# Profiling
re_path(
r"^profiling/",
|
145e873a652df78b9f40e609d0f780ba5bd182f3
|
2024-12-16 23:15:11
|
Michelle Zhang
|
ref(flags): don't show feature flag section on any issues besides errors (#82119)
| false
|
don't show feature flag section on any issues besides errors (#82119)
|
ref
|
diff --git a/static/app/components/events/featureFlags/eventFeatureFlagList.tsx b/static/app/components/events/featureFlags/eventFeatureFlagList.tsx
index 550a4d2b3e8ca7..1e9380f6131a91 100644
--- a/static/app/components/events/featureFlags/eventFeatureFlagList.tsx
+++ b/static/app/components/events/featureFlags/eventFeatureFlagList.tsx
@@ -24,7 +24,7 @@ import {featureFlagOnboardingPlatforms} from 'sentry/data/platformCategories';
import {IconMegaphone, IconSearch} from 'sentry/icons';
import {t} from 'sentry/locale';
import type {Event, FeatureFlag} from 'sentry/types/event';
-import type {Group} from 'sentry/types/group';
+import {type Group, IssueCategory} from 'sentry/types/group';
import type {Project} from 'sentry/types/project';
import {trackAnalytics} from 'sentry/utils/analytics';
import {useFeedbackForm} from 'sentry/utils/useFeedbackForm';
@@ -197,6 +197,10 @@ export function EventFeatureFlagList({
}
}, [hasFlags, hydratedFlags.length, organization]);
+ if (group.issueCategory !== IssueCategory.ERROR) {
+ return null;
+ }
+
if (showCTA) {
return <FeatureFlagInlineCTA projectId={event.projectID} />;
}
|
b9ca8538dfd52ccfb9f8e70769bd3c13c0b5958b
|
2024-10-22 22:51:42
|
Dominik Buszowiecki
|
feat(insights): add domain view urls to new sidebar (#79500)
| false
|
add domain view urls to new sidebar (#79500)
|
feat
|
diff --git a/static/app/components/nav/config.tsx b/static/app/components/nav/config.tsx
index 27504b725927bf..432d6077bfac42 100644
--- a/static/app/components/nav/config.tsx
+++ b/static/app/components/nav/config.tsx
@@ -1,4 +1,4 @@
-import type {NavConfig} from 'sentry/components/nav/utils';
+import type {NavConfig, NavSidebarItem} from 'sentry/components/nav/utils';
import {
IconDashboard,
IconGraph,
@@ -14,6 +14,22 @@ import type {Organization} from 'sentry/types/organization';
import {getDiscoverLandingUrl} from 'sentry/utils/discover/urls';
import {MODULE_BASE_URLS} from 'sentry/views/insights/common/utils/useModuleURL';
import {MODULE_SIDEBAR_TITLE as MODULE_TITLE_HTTP} from 'sentry/views/insights/http/settings';
+import {
+ AI_LANDING_SUB_PATH,
+ AI_LANDING_TITLE,
+} from 'sentry/views/insights/pages/ai/settings';
+import {
+ BACKEND_LANDING_SUB_PATH,
+ BACKEND_LANDING_TITLE,
+} from 'sentry/views/insights/pages/backend/settings';
+import {
+ FRONTEND_LANDING_SUB_PATH,
+ FRONTEND_LANDING_TITLE,
+} from 'sentry/views/insights/pages/frontend/settings';
+import {
+ MOBILE_LANDING_SUB_PATH,
+ MOBILE_LANDING_TITLE,
+} from 'sentry/views/insights/pages/mobile/settings';
import {INSIGHTS_BASE_URL, MODULE_TITLES} from 'sentry/views/insights/settings';
import {getSearchForIssueGroup, IssueGroup} from 'sentry/views/issueList/utils';
@@ -26,6 +42,84 @@ import {getSearchForIssueGroup, IssueGroup} from 'sentry/views/issueList/utils';
export function createNavConfig({organization}: {organization: Organization}): NavConfig {
const prefix = `organizations/${organization.slug}`;
const insightsPrefix = `${prefix}/${INSIGHTS_BASE_URL}`;
+ const hasPerfDomainViews = organization.features.includes('insights-domain-view');
+
+ const insights: NavSidebarItem = {
+ label: t('Insights'),
+ icon: <IconGraph />,
+ feature: {features: 'insights-entry-points'},
+ submenu: [
+ {
+ label: MODULE_TITLE_HTTP,
+ to: `/${insightsPrefix}/${MODULE_BASE_URLS.http}/`,
+ },
+ {label: MODULE_TITLES.db, to: `/${insightsPrefix}/${MODULE_BASE_URLS.db}/`},
+ {
+ label: MODULE_TITLES.resource,
+ to: `/${insightsPrefix}/${MODULE_BASE_URLS.resource}/`,
+ },
+ {
+ label: MODULE_TITLES.app_start,
+ to: `/${insightsPrefix}/${MODULE_BASE_URLS.app_start}/`,
+ },
+ {
+ label: MODULE_TITLES['mobile-screens'],
+ to: `/${insightsPrefix}/${MODULE_BASE_URLS['mobile-screens']}/`,
+ feature: {features: 'insights-mobile-screens-module'},
+ },
+ {
+ label: MODULE_TITLES.vital,
+ to: `/${insightsPrefix}/${MODULE_BASE_URLS.vital}/`,
+ },
+ {
+ label: MODULE_TITLES.cache,
+ to: `/${insightsPrefix}/${MODULE_BASE_URLS.cache}/`,
+ },
+ {
+ label: MODULE_TITLES.queue,
+ to: `/${insightsPrefix}/${MODULE_BASE_URLS.queue}/`,
+ },
+ {
+ label: MODULE_TITLES.ai,
+ to: `/${insightsPrefix}/${MODULE_BASE_URLS.ai}/`,
+ feature: {features: 'insights-entry-points'},
+ },
+ ],
+ };
+
+ const perf: NavSidebarItem = {
+ label: t('Perf.'),
+ to: '/performance/',
+ icon: <IconLightning />,
+ feature: {
+ features: 'performance-view',
+ hookName: 'feature-disabled:performance-sidebar-item',
+ },
+ };
+
+ const perfDomainViews: NavSidebarItem = {
+ label: t('Perf.'),
+ icon: <IconLightning />,
+ feature: {features: 'insights-domain-view'},
+ submenu: [
+ {
+ label: FRONTEND_LANDING_TITLE,
+ to: `/${prefix}/performance/${FRONTEND_LANDING_SUB_PATH}/`,
+ },
+ {
+ label: BACKEND_LANDING_TITLE,
+ to: `/${prefix}/performance/${BACKEND_LANDING_SUB_PATH}/`,
+ },
+ {
+ label: AI_LANDING_TITLE,
+ to: `/${prefix}/performance/${AI_LANDING_SUB_PATH}/`,
+ },
+ {
+ label: MOBILE_LANDING_TITLE,
+ to: `/${prefix}/performance/${MOBILE_LANDING_SUB_PATH}/`,
+ },
+ ],
+ };
return {
main: [
@@ -100,57 +194,7 @@ export function createNavConfig({organization}: {organization: Organization}): N
{label: t('Crons'), to: `/${prefix}/crons/`},
],
},
- {
- label: t('Insights'),
- icon: <IconGraph />,
- feature: {features: 'insights-entry-points'},
- submenu: [
- {
- label: MODULE_TITLE_HTTP,
- to: `/${insightsPrefix}/${MODULE_BASE_URLS.http}/`,
- },
- {label: MODULE_TITLES.db, to: `/${insightsPrefix}/${MODULE_BASE_URLS.db}/`},
- {
- label: MODULE_TITLES.resource,
- to: `/${insightsPrefix}/${MODULE_BASE_URLS.resource}/`,
- },
- {
- label: MODULE_TITLES.app_start,
- to: `/${insightsPrefix}/${MODULE_BASE_URLS.app_start}/`,
- },
- {
- label: MODULE_TITLES['mobile-screens'],
- to: `/${insightsPrefix}/${MODULE_BASE_URLS['mobile-screens']}/`,
- feature: {features: 'insights-mobile-screens-module'},
- },
- {
- label: MODULE_TITLES.vital,
- to: `/${insightsPrefix}/${MODULE_BASE_URLS.vital}/`,
- },
- {
- label: MODULE_TITLES.cache,
- to: `/${insightsPrefix}/${MODULE_BASE_URLS.cache}/`,
- },
- {
- label: MODULE_TITLES.queue,
- to: `/${insightsPrefix}/${MODULE_BASE_URLS.queue}/`,
- },
- {
- label: MODULE_TITLES.ai,
- to: `/${insightsPrefix}/${MODULE_BASE_URLS.ai}/`,
- feature: {features: 'insights-entry-points'},
- },
- ],
- },
- {
- label: t('Perf.'),
- to: '/performance/',
- icon: <IconLightning />,
- feature: {
- features: 'performance-view',
- hookName: 'feature-disabled:performance-sidebar-item',
- },
- },
+ ...(hasPerfDomainViews ? [perfDomainViews] : [insights, perf]),
{
label: t('Boards'),
to: '/dashboards/',
|
69569a3453883eebf5f2487d7f98942232e309f5
|
2021-02-17 21:11:40
|
Matej Minar
|
fix(ui): Fix user feedback docs link (#23907)
| false
|
Fix user feedback docs link (#23907)
|
fix
|
diff --git a/src/sentry/static/sentry/app/views/userFeedback/userFeedbackEmpty.tsx b/src/sentry/static/sentry/app/views/userFeedback/userFeedbackEmpty.tsx
index ff3aa0bd048504..3a1dad3bd1eb8a 100644
--- a/src/sentry/static/sentry/app/views/userFeedback/userFeedbackEmpty.tsx
+++ b/src/sentry/static/sentry/app/views/userFeedback/userFeedbackEmpty.tsx
@@ -108,7 +108,7 @@ class UserFeedbackEmpty extends React.Component<Props> {
eventName: 'User Feedback Docs Clicked',
})
}
- href="https://docs.sentry.io/enriching-error-data/user-feedback/"
+ href="https://docs.sentry.io/platform-redirect/?next=/enriching-error-data/user-feedback/"
>
{t('Read the docs')}
</Button>
|
08e6af18230aed7dea5aa6219f702cb16b385db3
|
2021-06-10 18:44:38
|
Armen Zambrano G
|
ref(build): Set PIP_NO_CACHE_DIR to 1 instead of off (#26502)
| false
|
Set PIP_NO_CACHE_DIR to 1 instead of off (#26502)
|
ref
|
diff --git a/docker/Dockerfile b/docker/Dockerfile
index 6d8106ac56d514..7964ff216c822b 100644
--- a/docker/Dockerfile
+++ b/docker/Dockerfile
@@ -35,7 +35,7 @@ RUN set -x \
# Sane defaults for pip
ENV \
- PIP_NO_CACHE_DIR=off \
+ PIP_NO_CACHE_DIR=1 \
PIP_DISABLE_PIP_VERSION_CHECK=1 \
# Sentry config params
SENTRY_CONF=/etc/sentry \
diff --git a/docker/builder.dockerfile b/docker/builder.dockerfile
index eb90fce519edea..75da986d4ab017 100644
--- a/docker/builder.dockerfile
+++ b/docker/builder.dockerfile
@@ -8,7 +8,7 @@ LABEL org.opencontainers.image.vendor="Functional Software, Inc."
LABEL org.opencontainers.image.authors="[email protected]"
# Sane defaults for pip
-ENV PIP_NO_CACHE_DIR=off \
+ENV PIP_NO_CACHE_DIR=1 \
PIP_DISABLE_PIP_VERSION_CHECK=1
RUN apt-get update && apt-get install -y --no-install-recommends \
|
dfeb6019edee50f6c04bc01cb553343b8c3a3009
|
2025-03-07 19:50:22
|
anthony sottile
|
ref: fix types for endpoints.organization_projects (#86537)
| false
|
fix types for endpoints.organization_projects (#86537)
|
ref
|
diff --git a/pyproject.toml b/pyproject.toml
index 5d5ad1964b63f9..c6d76566f6505b 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -117,7 +117,6 @@ module = [
"sentry.api.endpoints.organization_events_facets_performance",
"sentry.api.endpoints.organization_events_meta",
"sentry.api.endpoints.organization_events_spans_performance",
- "sentry.api.endpoints.organization_projects",
"sentry.api.endpoints.organization_releases",
"sentry.api.endpoints.organization_search_details",
"sentry.api.endpoints.project_ownership",
diff --git a/src/sentry/api/endpoints/organization_projects.py b/src/sentry/api/endpoints/organization_projects.py
index 5576db94bc6a27..e5ab672e621d8e 100644
--- a/src/sentry/api/endpoints/organization_projects.py
+++ b/src/sentry/api/endpoints/organization_projects.py
@@ -1,6 +1,7 @@
from typing import Any
from django.db.models import Q
+from django.db.models.query import QuerySet
from drf_spectacular.utils import extend_schema
from rest_framework.exceptions import ParseError
from rest_framework.request import Request
@@ -81,6 +82,7 @@ def get(self, request: Request, organization) -> Response:
datasetName = request.GET.get("dataset", "discover")
dataset = get_dataset(datasetName)
+ queryset: QuerySet[Project]
if request.auth and not request.user.is_authenticated:
# TODO: remove this, no longer supported probably
if hasattr(request.auth, "project"):
@@ -116,8 +118,10 @@ def get(self, request: Request, organization) -> Response:
tokens = tokenize_query(query)
for key, value in tokens.items():
if key == "query":
- value = " ".join(value)
- queryset = queryset.filter(Q(name__icontains=value) | Q(slug__icontains=value))
+ value_s = " ".join(value)
+ queryset = queryset.filter(
+ Q(name__icontains=value_s) | Q(slug__icontains=value_s)
+ )
elif key == "id":
if all(v.isdigit() for v in value):
queryset = queryset.filter(id__in=value)
|
dbda812c12c058ea23052e04f799f250079e2429
|
2021-06-02 04:14:31
|
Chris Gårdenberg
|
fix(GithubEnterpriseIntegration): Adding Authorization-header for installations-request (#26281)
| false
|
Adding Authorization-header for installations-request (#26281)
|
fix
|
diff --git a/src/sentry/integrations/github_enterprise/integration.py b/src/sentry/integrations/github_enterprise/integration.py
index bbbe76bd08b427..42426a3257585d 100644
--- a/src/sentry/integrations/github_enterprise/integration.py
+++ b/src/sentry/integrations/github_enterprise/integration.py
@@ -311,8 +311,10 @@ def get_installation_info(self, installation_data, access_token, installation_id
resp = session.get(
"https://{}/api/v3/user/installations".format(installation_data["url"]),
- params={"access_token": access_token},
- headers={"Accept": "application/vnd.github.machine-man-preview+json"},
+ headers={
+ "Accept": "application/vnd.github.machine-man-preview+json",
+ "Authorization": f"token {access_token}",
+ },
verify=installation_data["verify_ssl"],
)
resp.raise_for_status()
diff --git a/tests/sentry/integrations/github_enterprise/test_integration.py b/tests/sentry/integrations/github_enterprise/test_integration.py
index e186788f43456c..c5191b3fe076c5 100644
--- a/tests/sentry/integrations/github_enterprise/test_integration.py
+++ b/tests/sentry/integrations/github_enterprise/test_integration.py
@@ -98,6 +98,7 @@ def assert_setup_flow(
responses.GET,
self.base_url + "/user/installations",
json={"installations": [{"id": installation_id}]},
+ match_querystring=True,
)
resp = self.client.get(
|
11b1cfa9afa2e66096c2361781e6fe37f196d0f0
|
2019-06-04 22:10:25
|
Billy Vong
|
feat(api): Add searching for org projects by slug(s) (#13513)
| false
|
Add searching for org projects by slug(s) (#13513)
|
feat
|
diff --git a/src/sentry/api/endpoints/organization_projects.py b/src/sentry/api/endpoints/organization_projects.py
index e4a38393d361e7..a6037b1a2d200d 100644
--- a/src/sentry/api/endpoints/organization_projects.py
+++ b/src/sentry/api/endpoints/organization_projects.py
@@ -106,6 +106,8 @@ def get(self, request, organization):
queryset = queryset.filter(Q(name__icontains=value) | Q(slug__icontains=value))
elif key == 'id':
queryset = queryset.filter(id__in=value)
+ elif key == 'slug':
+ queryset = queryset.filter(slug__in=value)
elif key == "team":
team_list = list(Team.objects.filter(slug__in=value))
queryset = queryset.filter(teams__in=team_list)
diff --git a/tests/sentry/api/endpoints/test_organization_projects.py b/tests/sentry/api/endpoints/test_organization_projects.py
index b61ffa9a51f7b3..0b80017b07540d 100644
--- a/tests/sentry/api/endpoints/test_organization_projects.py
+++ b/tests/sentry/api/endpoints/test_organization_projects.py
@@ -81,6 +81,22 @@ def test_search_by_ids(self):
self.check_valid_response(response, [project_bar, project_foo])
+ def test_search_by_slugs(self):
+ self.login_as(user=self.user)
+
+ project_bar = self.create_project(teams=[self.team], name='bar', slug='bar')
+ project_foo = self.create_project(teams=[self.team], name='foo', slug='foo')
+ self.create_project(teams=[self.team], name='baz', slug='baz')
+
+ path = u'{}?query=slug:{}'.format(self.path, project_foo.slug)
+ response = self.client.get(path)
+ self.check_valid_response(response, [project_foo])
+
+ path = u'{}?query=slug:{} slug:{}'.format(self.path, project_bar.slug, project_foo.slug)
+ response = self.client.get(path)
+
+ self.check_valid_response(response, [project_bar, project_foo])
+
def test_bookmarks_appear_first_across_pages(self):
self.login_as(user=self.user)
|
b52984d8cff42fb0f6271f9823c7031d7ad616ae
|
2024-02-02 05:16:16
|
Julia Hoge
|
feat(priority): Add priorityLockedAt to serializer (#64430)
| false
|
Add priorityLockedAt to serializer (#64430)
|
feat
|
diff --git a/src/sentry/api/serializers/models/group.py b/src/sentry/api/serializers/models/group.py
index 7f53d482441742..eef42d5ffae6e0 100644
--- a/src/sentry/api/serializers/models/group.py
+++ b/src/sentry/api/serializers/models/group.py
@@ -353,6 +353,7 @@ def serialize(
if features.has("projects:issue-priority", obj.project, actor=None):
priority_label = PRIORITY_LEVEL_TO_STR[obj.priority] if obj.priority else None
group_dict["priority"] = priority_label
+ group_dict["priorityLockedAt"] = obj.priority_locked_at
# This attribute is currently feature gated
if "is_unhandled" in attrs:
diff --git a/tests/snuba/api/serializers/test_group.py b/tests/snuba/api/serializers/test_group.py
index 65f9c5d0615f34..63244dc6e5f9bb 100644
--- a/tests/snuba/api/serializers/test_group.py
+++ b/tests/snuba/api/serializers/test_group.py
@@ -52,6 +52,7 @@ def test_priority_no_ff(self):
group = self.create_group()
result = serialize(group, outside_user, serializer=GroupSerializerSnuba())
assert "priority" not in result
+ assert "priorityLockedAt" not in result
@with_feature("projects:issue-priority")
def test_priority_high(self):
@@ -73,6 +74,7 @@ def test_priority_none(self):
group = self.create_group()
result = serialize(group, outside_user, serializer=GroupSerializerSnuba())
assert result["priority"] is None
+ assert result["priorityLockedAt"] is None
def test_is_ignored_with_expired_snooze(self):
now = django_timezone.now()
|
68a1f39b2f0919cb12e5f12c8b334963926502c3
|
2023-11-27 23:15:11
|
Stephen Cefali
|
feat(notifications): remove logic to remove notificationsetting rows when the user uninstalls slack (#60535)
| false
|
remove logic to remove notificationsetting rows when the user uninstalls slack (#60535)
|
feat
|
diff --git a/src/sentry/integrations/slack/integration.py b/src/sentry/integrations/slack/integration.py
index acde5d9c1e45cb..f73d24f4248ad6 100644
--- a/src/sentry/integrations/slack/integration.py
+++ b/src/sentry/integrations/slack/integration.py
@@ -16,12 +16,7 @@
)
from sentry.models.integrations.integration import Integration
from sentry.pipeline import NestedPipelineView
-from sentry.services.hybrid_cloud.notifications import notifications_service
-from sentry.services.hybrid_cloud.organization import (
- RpcOrganizationSummary,
- RpcUserOrganizationContext,
- organization_service,
-)
+from sentry.services.hybrid_cloud.organization import RpcOrganizationSummary
from sentry.shared_integrations.exceptions import ApiError, IntegrationError
from sentry.tasks.integrations.slack import link_slack_user_identities
from sentry.utils.http import absolute_uri
@@ -87,21 +82,6 @@ def get_config_data(self) -> Mapping[str, str]:
)
return {"installationType": metadata_.get("installation_type", default_installation)}
- def uninstall(self) -> None:
- """
- Delete all parent-specific notification settings. For each user and team,
- if this is their ONLY Slack integration, set their parent-independent
- Slack notification setting to NEVER.
- """
- org_context: RpcUserOrganizationContext | None = (
- organization_service.get_organization_by_id(id=self.organization_id, user_id=None)
- )
- if org_context:
- notifications_service.uninstall_slack_settings(
- organization_id=self.organization_id,
- project_ids=[p.id for p in org_context.organization.projects],
- )
-
class SlackIntegrationProvider(IntegrationProvider):
key = "slack"
diff --git a/src/sentry/notifications/manager.py b/src/sentry/notifications/manager.py
index e465ddc05daa61..3d8e0db80f0302 100644
--- a/src/sentry/notifications/manager.py
+++ b/src/sentry/notifications/manager.py
@@ -2,7 +2,7 @@
import logging
from collections import defaultdict
-from typing import TYPE_CHECKING, Iterable, List, Mapping, MutableSet, Optional, Set, Union
+from typing import TYPE_CHECKING, Iterable, Mapping, MutableSet, Optional, Set, Union
from django.db import router, transaction
from django.db.models import Q, QuerySet
@@ -20,7 +20,6 @@
NOTIFICATION_SCOPE_TYPE,
NOTIFICATION_SETTING_OPTION_VALUES,
NOTIFICATION_SETTING_TYPES,
- VALID_VALUES_FOR_KEY,
VALID_VALUES_FOR_KEY_V2,
NotificationScopeEnum,
NotificationScopeType,
@@ -485,39 +484,3 @@ def update_provider_settings(self, user_id: int | None, team_id: int | None):
**base_query,
type__in=[NOTIFICATION_SETTING_TYPES[type] for type in types_to_delete],
).delete()
-
- def remove_parent_settings_for_organization(
- self, organization_id: int, project_ids: List[int], provider: ExternalProviders
- ) -> None:
- """Delete all parent-specific notification settings referencing this organization."""
- kwargs = {}
- kwargs["provider"] = provider.value
-
- self.filter(
- Q(scope_type=NotificationScopeType.PROJECT.value, scope_identifier__in=project_ids)
- | Q(
- scope_type=NotificationScopeType.ORGANIZATION.value,
- scope_identifier=organization_id,
- ),
- **kwargs,
- ).delete()
-
- def disable_settings_for_users(
- self, provider: ExternalProviders, users: Iterable[User]
- ) -> None:
- """
- Given a list of users, overwrite all of their parent-independent
- notification settings to NEVER.
- TODO(mgaeta): Django 3 has self.bulk_create() which would allow us to do
- this in a single query.
- """
- for user in users:
- for type in VALID_VALUES_FOR_KEY.keys():
- self.update_or_create(
- provider=provider.value,
- type=type.value,
- scope_type=NotificationScopeType.USER.value,
- scope_identifier=user.id,
- user_id=user.id,
- defaults={"value": NotificationSettingOptionValues.NEVER.value},
- )
diff --git a/src/sentry/services/hybrid_cloud/notifications/impl.py b/src/sentry/services/hybrid_cloud/notifications/impl.py
index fc4eaf3ee40c25..0cb28f7deef1c5 100644
--- a/src/sentry/services/hybrid_cloud/notifications/impl.py
+++ b/src/sentry/services/hybrid_cloud/notifications/impl.py
@@ -35,17 +35,6 @@
class DatabaseBackedNotificationsService(NotificationsService):
- def uninstall_slack_settings(self, organization_id: int, project_ids: List[int]) -> None:
- provider = ExternalProviders.SLACK
- users = User.objects.get_users_with_only_one_integration_for_provider(
- provider, organization_id
- )
-
- NotificationSetting.objects.remove_parent_settings_for_organization(
- organization_id, project_ids, provider
- )
- NotificationSetting.objects.disable_settings_for_users(provider, users)
-
def update_settings(
self,
*,
diff --git a/src/sentry/services/hybrid_cloud/notifications/service.py b/src/sentry/services/hybrid_cloud/notifications/service.py
index 432c53e3ff1522..f803ce27436813 100644
--- a/src/sentry/services/hybrid_cloud/notifications/service.py
+++ b/src/sentry/services/hybrid_cloud/notifications/service.py
@@ -74,15 +74,6 @@ def update_notification_options(
) -> None:
pass
- @rpc_method
- @abstractmethod
- def uninstall_slack_settings(
- self,
- organization_id: int,
- project_ids: List[int],
- ) -> None:
- pass
-
@rpc_method
@abstractmethod
def remove_notification_settings_for_team(
diff --git a/tests/sentry/integrations/slack/test_uninstall.py b/tests/sentry/integrations/slack/test_uninstall.py
deleted file mode 100644
index e013d893549e0b..00000000000000
--- a/tests/sentry/integrations/slack/test_uninstall.py
+++ /dev/null
@@ -1,132 +0,0 @@
-from typing import Optional
-
-from sentry.constants import ObjectStatus
-from sentry.models.integrations.integration import Integration
-from sentry.models.integrations.organization_integration import OrganizationIntegration
-from sentry.models.notificationsetting import NotificationSetting
-from sentry.models.project import Project
-from sentry.models.scheduledeletion import ScheduledDeletion
-from sentry.models.user import User
-from sentry.notifications.defaults import NOTIFICATION_SETTING_DEFAULTS
-from sentry.notifications.types import NotificationSettingOptionValues, NotificationSettingTypes
-from sentry.testutils.cases import APITestCase
-from sentry.testutils.silo import control_silo_test
-from sentry.types.integrations import ExternalProviders
-
-
-@control_silo_test
-class SlackUninstallTest(APITestCase):
- """TODO(mgaeta): Extract the endpoint's DELETE logic to a helper and use it instead of API."""
-
- endpoint = "sentry-api-0-organization-integration-details"
- method = "delete"
-
- def setUp(self) -> None:
- self.integration = self.create_slack_integration(self.organization)
- self.login_as(self.user)
-
- def uninstall(self) -> None:
- org_integration = OrganizationIntegration.objects.get(
- integration=self.integration, organization_id=self.organization.id
- )
-
- with self.tasks():
- self.get_success_response(self.organization.slug, self.integration.id)
-
- assert Integration.objects.filter(id=self.integration.id).exists()
-
- assert not OrganizationIntegration.objects.filter(
- integration=self.integration,
- organization_id=self.organization.id,
- status=ObjectStatus.ACTIVE,
- ).exists()
- assert ScheduledDeletion.objects.filter(
- model_name="OrganizationIntegration", object_id=org_integration.id
- ).exists()
-
- def get_setting(
- self, user: User, provider: ExternalProviders, parent: Optional[Project] = None
- ) -> NotificationSettingOptionValues:
- type = NotificationSettingTypes.ISSUE_ALERTS
- parent_specific_setting = NotificationSetting.objects.get_settings(
- provider=provider, type=type, user_id=user.id, project=parent
- )
- if parent_specific_setting != NotificationSettingOptionValues.DEFAULT:
- return parent_specific_setting
- parent_independent_setting = NotificationSetting.objects.get_settings(
- provider=provider,
- type=type,
- user_id=user.id,
- )
- if parent_independent_setting != NotificationSettingOptionValues.DEFAULT:
- return parent_independent_setting
-
- return NOTIFICATION_SETTING_DEFAULTS[provider][type]
-
- def assert_settings(
- self, provider: ExternalProviders, value: NotificationSettingOptionValues
- ) -> None:
- assert self.get_setting(self.user, provider) == value
- assert self.get_setting(self.user, provider, parent=self.project) == value
-
- def set_setting(
- self, provider: ExternalProviders, value: NotificationSettingOptionValues
- ) -> None:
- type = NotificationSettingTypes.ISSUE_ALERTS
- NotificationSetting.objects.update_settings(provider, type, value, user_id=self.user.id)
- NotificationSetting.objects.update_settings(
- provider, type, value, user_id=self.user.id, project=self.project
- )
-
- def test_uninstall_email_only(self):
- self.uninstall()
-
- self.assert_settings(ExternalProviders.EMAIL, NotificationSettingOptionValues.ALWAYS)
- self.assert_settings(ExternalProviders.SLACK, NotificationSettingOptionValues.NEVER)
-
- def test_uninstall_slack_and_email(self):
- self.set_setting(ExternalProviders.SLACK, NotificationSettingOptionValues.ALWAYS)
-
- self.uninstall()
-
- self.assert_settings(ExternalProviders.EMAIL, NotificationSettingOptionValues.ALWAYS)
- self.assert_settings(ExternalProviders.SLACK, NotificationSettingOptionValues.NEVER)
-
- def test_uninstall_slack_only(self):
- self.set_setting(ExternalProviders.EMAIL, NotificationSettingOptionValues.NEVER)
- self.set_setting(ExternalProviders.SLACK, NotificationSettingOptionValues.ALWAYS)
-
- self.uninstall()
-
- self.assert_settings(ExternalProviders.EMAIL, NotificationSettingOptionValues.NEVER)
- self.assert_settings(ExternalProviders.SLACK, NotificationSettingOptionValues.NEVER)
-
- def test_uninstall_generates_settings_with_userid(self):
- self.uninstall()
-
- self.assert_settings(ExternalProviders.SLACK, NotificationSettingOptionValues.NEVER)
- # Ensure uninstall sets user_id.
- settings = NotificationSetting.objects.find_settings(
- provider=ExternalProviders.SLACK,
- type=NotificationSettingTypes.ISSUE_ALERTS,
- user_id=self.user.id,
- )
- assert settings[0].user_id == self.user.id
-
- def test_uninstall_with_multiple_organizations(self):
- organization = self.create_organization(owner=self.user)
- integration = self.create_slack_integration(organization, "TXXXXXXX2")
-
- self.set_setting(ExternalProviders.EMAIL, NotificationSettingOptionValues.NEVER)
- self.set_setting(ExternalProviders.SLACK, NotificationSettingOptionValues.ALWAYS)
-
- self.uninstall()
-
- # No changes to second organization.
- assert Integration.objects.filter(id=integration.id).exists()
- assert OrganizationIntegration.objects.filter(
- integration=integration, organization_id=organization.id
- ).exists()
-
- self.assert_settings(ExternalProviders.EMAIL, NotificationSettingOptionValues.NEVER)
- self.assert_settings(ExternalProviders.SLACK, NotificationSettingOptionValues.ALWAYS)
|
d04e5e1c0a919d6da881d77e5827d58f5f95b917
|
2025-03-17 18:20:12
|
Ogi
|
fix(demo-mode): disable crons owner dropdown (#87172)
| false
|
disable crons owner dropdown (#87172)
|
fix
|
diff --git a/static/app/views/monitors/components/ownerFilter.tsx b/static/app/views/monitors/components/ownerFilter.tsx
index 64c130f1c041d0..230016b5ae8bd0 100644
--- a/static/app/views/monitors/components/ownerFilter.tsx
+++ b/static/app/views/monitors/components/ownerFilter.tsx
@@ -1,5 +1,6 @@
import {CompactSelect} from 'sentry/components/compactSelect';
import {t} from 'sentry/locale';
+import {isDemoModeEnabled} from 'sentry/utils/demoMode';
import {useOwnerOptions} from 'sentry/utils/useOwnerOptions';
import {useOwners} from 'sentry/utils/useOwners';
@@ -35,6 +36,7 @@ export function OwnerFilter({selectedOwners, onChangeFilter}: OwnerFilterProps)
clearable
searchable
loading={fetching}
+ disabled={isDemoModeEnabled()}
menuTitle={t('Filter owners')}
options={[{label: t('Suggested'), options: suggestedOptions}, ...options]}
value={selectedOwners}
|
929698357d18cdfbe87905062b6304c06627db15
|
2022-03-31 00:18:03
|
Vu Luong
|
ref(alert): Add trailingItems prop to <Alert /> (#32781)
| false
|
Add trailingItems prop to <Alert /> (#32781)
|
ref
|
diff --git a/docs-ui/stories/components/alert.stories.js b/docs-ui/stories/components/alert.stories.js
index 503b015277190d..6202a96551e268 100644
--- a/docs-ui/stories/components/alert.stories.js
+++ b/docs-ui/stories/components/alert.stories.js
@@ -1,6 +1,7 @@
import styled from '@emotion/styled';
import Alert from 'sentry/components/alert';
+import Button from 'sentry/components/button';
import ExternalLink from 'sentry/components/links/externalLink';
import space from 'sentry/styles/space';
@@ -57,11 +58,41 @@ export const WithIcons = () => (
</Grid>
);
-WithIcons.storyName = 'With Icons';
+WithIcons.storyName = 'With Leading Icons';
WithIcons.parameters = {
docs: {
description: {
- story: 'Inline alert messages',
+ story: 'Optional leading icon via the `showIcon` prop',
+ },
+ },
+};
+
+export const WithTrailingItems = () => (
+ <Grid>
+ <Alert type="info" trailingItems={<Button size="xsmall">Trailing Button</Button>}>
+ <ExternalLink href="#">Info message with a url</ExternalLink>
+ </Alert>
+
+ <Alert type="success" trailingItems={<Button size="xsmall">Trailing Button</Button>}>
+ Success message without a url
+ </Alert>
+
+ <Alert type="warning" trailingItems={<Button size="xsmall">Trailing Button</Button>}>
+ Warning message
+ </Alert>
+
+ <Alert type="error" trailingItems={<Button size="xsmall">Trailing Button</Button>}>
+ Background workers haven't checked in recently. This can mean an issue with your
+ configuration or a serious backlog in tasks.
+ </Alert>
+ </Grid>
+);
+
+WithTrailingItems.storyName = 'With Trailing Items';
+WithTrailingItems.parameters = {
+ docs: {
+ description: {
+ story: 'Optional trailing items via the `trailingItems` prop',
},
},
};
diff --git a/static/app/components/alert.tsx b/static/app/components/alert.tsx
index 9309ec39f00bae..c436936b0b49e7 100644
--- a/static/app/components/alert.tsx
+++ b/static/app/components/alert.tsx
@@ -5,6 +5,7 @@ import classNames from 'classnames';
import {IconCheckmark, IconChevron, IconInfo, IconNot, IconWarning} from 'sentry/icons';
import space from 'sentry/styles/space';
+import {defined} from 'sentry/utils';
import {Theme} from 'sentry/utils/theme';
export interface AlertProps extends React.HTMLAttributes<HTMLDivElement> {
@@ -12,21 +13,33 @@ export interface AlertProps extends React.HTMLAttributes<HTMLDivElement> {
opaque?: boolean;
showIcon?: boolean;
system?: boolean;
+ trailingItems?: React.ReactNode;
type?: keyof Theme['alert'];
}
const DEFAULT_TYPE = 'info';
-const IconWrapper = styled('span')`
+const IconWrapper = styled('div')`
display: flex;
height: calc(${p => p.theme.fontSizeMedium} * ${p => p.theme.text.lineHeightBody});
margin-right: ${space(1)};
align-items: center;
`;
+const TrailingItems = styled('div')`
+ display: grid;
+ grid-auto-flow: column;
+ grid-template-rows: 100%;
+ align-items: center;
+ gap: ${space(1)};
+ height: calc(${p => p.theme.fontSizeMedium} * ${p => p.theme.text.lineHeightBody});
+ margin-left: ${space(1)};
+`;
+
const alertStyles = ({
theme,
type = DEFAULT_TYPE,
+ trailingItems,
system,
opaque,
expand,
@@ -45,6 +58,8 @@ const alertStyles = ({
? `linear-gradient(${alertColors.backgroundLight}, ${alertColors.backgroundLight}), linear-gradient(${theme.background}, ${theme.background})`
: `${alertColors.backgroundLight}`};
+ ${defined(trailingItems) && `padding-right: ${space(1.5)};`}
+
a:not([role='button']) {
color: ${theme.textColor};
text-decoration-color: ${theme.translucentBorder};
@@ -116,6 +131,7 @@ const Alert = styled(
className,
showIcon = false,
expand,
+ trailingItems,
opaque: _opaque, // don't forward to `div`
system: _system, // don't forward to `div`
...props
@@ -147,7 +163,12 @@ const Alert = styled(
<MessageContainer>
{showIcon && <IconWrapper>{getIcon()}</IconWrapper>}
<StyledTextBlock>{children}</StyledTextBlock>
- {showExpand && <ExpandIcon isExpanded={isExpanded} />}
+ {(showExpand || defined(trailingItems)) && (
+ <TrailingItems>
+ {trailingItems}
+ {showExpand && <ExpandIcon isExpanded={isExpanded} />}
+ </TrailingItems>
+ )}
</MessageContainer>
{showExpandItems && (
<ExpandContainer>
diff --git a/static/app/components/createAlertButton.tsx b/static/app/components/createAlertButton.tsx
index 4abd7ca987f6fc..43ff7fc9aa7d0b 100644
--- a/static/app/components/createAlertButton.tsx
+++ b/static/app/components/createAlertButton.tsx
@@ -120,7 +120,19 @@ function IncompatibleQueryAlert({
};
return (
- <StyledAlert type="warning" showIcon>
+ <StyledAlert
+ type="warning"
+ showIcon
+ trailingItems={
+ <Button
+ icon={<IconClose size="sm" />}
+ aria-label={t('Close')}
+ size="zero"
+ onClick={onClose}
+ borderless
+ />
+ }
+ >
{totalErrors === 1 && (
<React.Fragment>
{hasProjectError &&
@@ -172,13 +184,6 @@ function IncompatibleQueryAlert({
</StyledUnorderedList>
</React.Fragment>
)}
- <StyledCloseButton
- icon={<IconClose size="sm" />}
- aria-label={t('Close')}
- size="zero"
- onClick={onClose}
- borderless
- />
</StyledAlert>
);
}
@@ -438,15 +443,3 @@ const StyledCode = styled('code')`
background-color: transparent;
padding: 0;
`;
-
-const StyledCloseButton = styled(Button)`
- transition: opacity 0.1s linear;
- position: absolute;
- top: 3px;
- right: 0;
-
- &:hover,
- &:focus {
- background-color: transparent;
- }
-`;
diff --git a/static/app/components/forms/formField/index.tsx b/static/app/components/forms/formField/index.tsx
index 40d96918c7f7bc..3b4b425d277b46 100644
--- a/static/app/components/forms/formField/index.tsx
+++ b/static/app/components/forms/formField/index.tsx
@@ -4,7 +4,6 @@ import {Observer} from 'mobx-react';
import Alert from 'sentry/components/alert';
import Button from 'sentry/components/button';
-import ButtonBar from 'sentry/components/buttonBar';
import Field, {FieldProps} from 'sentry/components/forms/field';
import FieldControl from 'sentry/components/forms/field/fieldControl';
import FieldErrorReason from 'sentry/components/forms/field/fieldErrorReason';
@@ -14,7 +13,6 @@ import FormModel, {MockModel} from 'sentry/components/forms/model';
import ReturnButton from 'sentry/components/forms/returnButton';
import PanelAlert from 'sentry/components/panels/panelAlert';
import {t} from 'sentry/locale';
-import space from 'sentry/styles/space';
import {defined} from 'sentry/utils';
import {sanitizeQuerySelector} from 'sentry/utils/sanitizeQuerySelector';
@@ -406,24 +404,26 @@ class FormField extends React.Component<FormFieldProps> {
}
return (
- <PanelAlert type={saveMessageAlertType}>
- <MessageAndActions>
- <div>
- {typeof saveMessage === 'function'
- ? saveMessage({...props, value})
- : saveMessage}
- </div>
- <ButtonBar gap={1}>
- <Button onClick={this.handleCancelField}>{t('Cancel')}</Button>
+ <PanelAlert
+ type={saveMessageAlertType}
+ trailingItems={
+ <React.Fragment>
+ <Button onClick={this.handleCancelField} size="xsmall">
+ {t('Cancel')}
+ </Button>
<Button
priority="primary"
- type="button"
+ size="xsmall"
onClick={this.handleSaveField}
>
{t('Save')}
</Button>
- </ButtonBar>
- </MessageAndActions>
+ </React.Fragment>
+ }
+ >
+ {typeof saveMessage === 'function'
+ ? saveMessage({...props, value})
+ : saveMessage}
</PanelAlert>
);
}}
@@ -464,13 +464,6 @@ class FormField extends React.Component<FormFieldProps> {
export default FormField;
-const MessageAndActions = styled('div')`
- display: grid;
- grid-template-columns: 1fr max-content;
- gap: ${space(2)};
- align-items: flex-start;
-`;
-
const StyledReturnButton = styled(ReturnButton)`
position: absolute;
right: 0;
diff --git a/static/app/components/globalSdkUpdateAlert.tsx b/static/app/components/globalSdkUpdateAlert.tsx
index a232efef7cbb96..68a1fa74aa7484 100644
--- a/static/app/components/globalSdkUpdateAlert.tsx
+++ b/static/app/components/globalSdkUpdateAlert.tsx
@@ -1,12 +1,10 @@
-import * as React from 'react';
-import styled from '@emotion/styled';
+import {Fragment, useCallback, useEffect, useState} from 'react';
import {promptsCheck, promptsUpdate} from 'sentry/actionCreators/prompts';
import SidebarPanelActions from 'sentry/actions/sidebarPanelActions';
import Alert, {AlertProps} from 'sentry/components/alert';
import {ALL_ACCESS_PROJECTS} from 'sentry/constants/pageFilters';
import {t} from 'sentry/locale';
-import space from 'sentry/styles/space';
import {PageFilters, ProjectSdkUpdates} from 'sentry/types';
import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
import {promptIsDismissed} from 'sentry/utils/promptIsDismissed';
@@ -29,9 +27,9 @@ function InnerGlobalSdkUpdateAlert(
const api = useApi();
const organization = useOrganization();
- const [showUpdateAlert, setShowUpdateAlert] = React.useState<boolean>(false);
+ const [showUpdateAlert, setShowUpdateAlert] = useState<boolean>(false);
- const handleSnoozePrompt = React.useCallback(() => {
+ const handleSnoozePrompt = useCallback(() => {
promptsUpdate(api, {
organizationId: organization.id,
feature: 'sdk_updates',
@@ -42,12 +40,12 @@ function InnerGlobalSdkUpdateAlert(
setShowUpdateAlert(false);
}, [api, organization]);
- const handleReviewUpdatesClick = React.useCallback(() => {
+ const handleReviewUpdatesClick = useCallback(() => {
SidebarPanelActions.activatePanel(SidebarPanelKey.Broadcasts);
trackAdvancedAnalyticsEvent('sdk_updates.clicked', {organization});
}, []);
- React.useEffect(() => {
+ useEffect(() => {
trackAdvancedAnalyticsEvent('sdk_updates.seen', {organization});
let isUnmounted = false;
@@ -89,12 +87,11 @@ function InnerGlobalSdkUpdateAlert(
}
return (
- <Alert type="info" showIcon>
- <Content>
- {t(
- `You have outdated SDKs in your projects. Update them for important fixes and features.`
- )}
- <Actions>
+ <Alert
+ type="info"
+ showIcon
+ trailingItems={
+ <Fragment>
<Button
priority="link"
size="zero"
@@ -103,31 +100,20 @@ function InnerGlobalSdkUpdateAlert(
>
{t('Remind me later')}
</Button>
- |
+ <span>|</span>
<Button priority="link" size="zero" onClick={handleReviewUpdatesClick}>
{t('Review updates')}
</Button>
- </Actions>
- </Content>
+ </Fragment>
+ }
+ >
+ {t(
+ `You have outdated SDKs in your projects. Update them for important fixes and features.`
+ )}
</Alert>
);
}
-const Content = styled('div')`
- display: flex;
- flex-wrap: wrap;
-
- @media (min-width: ${p => p.theme.breakpoints[0]}) {
- justify-content: space-between;
- }
-`;
-
-const Actions = styled('div')`
- display: grid;
- grid-template-columns: repeat(3, max-content);
- gap: ${space(1)};
-`;
-
const WithSdkUpdatesGlobalSdkUpdateAlert = withSdkUpdates(
withPageFilters(InnerGlobalSdkUpdateAlert)
);
diff --git a/static/app/components/loadingError.tsx b/static/app/components/loadingError.tsx
index 176170a0529181..149904032523b7 100644
--- a/static/app/components/loadingError.tsx
+++ b/static/app/components/loadingError.tsx
@@ -4,9 +4,7 @@ import styled from '@emotion/styled';
import Alert from 'sentry/components/alert';
import Button from 'sentry/components/button';
import {Panel} from 'sentry/components/panels';
-import {IconInfo} from 'sentry/icons';
import {t} from 'sentry/locale';
-import space from 'sentry/styles/space';
type DefaultProps = {
message: React.ReactNode;
@@ -31,16 +29,18 @@ class LoadingError extends React.Component<Props> {
render() {
const {message, onRetry} = this.props;
return (
- <StyledAlert type="error">
- <Content>
- <IconInfo size="lg" />
- <div data-test-id="loading-error-message">{message}</div>
- {onRetry && (
+ <StyledAlert
+ type="error"
+ showIcon
+ trailingItems={
+ onRetry && (
<Button onClick={onRetry} type="button" priority="default" size="small">
{t('Retry')}
</Button>
- )}
- </Content>
+ )
+ }
+ >
+ {message}
</StyledAlert>
);
}
@@ -54,10 +54,3 @@ const StyledAlert = styled(Alert)`
border-width: 1px 0;
}
`;
-
-const Content = styled('div')`
- display: grid;
- gap: ${space(1)};
- grid-template-columns: min-content auto max-content;
- align-items: center;
-`;
diff --git a/static/app/components/organizations/pageFilters/desyncedFiltersAlert.tsx b/static/app/components/organizations/pageFilters/desyncedFiltersAlert.tsx
index 5fa70abf67fb90..31acceb697a133 100644
--- a/static/app/components/organizations/pageFilters/desyncedFiltersAlert.tsx
+++ b/static/app/components/organizations/pageFilters/desyncedFiltersAlert.tsx
@@ -1,11 +1,10 @@
-import {useState} from 'react';
+import {Fragment, useState} from 'react';
import {InjectedRouter} from 'react-router';
import styled from '@emotion/styled';
import {revertToPinnedFilters} from 'sentry/actionCreators/pageFilters';
import Alert from 'sentry/components/alert';
import Button from 'sentry/components/button';
-import ButtonBar from 'sentry/components/buttonBar';
import {IconClose} from 'sentry/icons';
import {t} from 'sentry/locale';
import PageFiltersStore from 'sentry/stores/pageFiltersStore';
@@ -31,14 +30,12 @@ export default function DesyncedFilterAlert({router}: Props) {
}
return (
- <Alert type="info" showIcon system>
- <AlertWrapper>
- <AlertText>
- {t(
- "You're viewing a shared link. Certain queries and filters have been automatically filled from URL parameters."
- )}
- </AlertText>
- <ButtonBar gap={1.5}>
+ <Alert
+ type="info"
+ showIcon
+ system
+ trailingItems={
+ <Fragment>
<RevertButton priority="link" size="zero" onClick={onRevertClick} borderless>
{t('Revert')}
</RevertButton>
@@ -49,21 +46,16 @@ export default function DesyncedFilterAlert({router}: Props) {
aria-label={t('Close Alert')}
onClick={() => setHideAlert(true)}
/>
- </ButtonBar>
- </AlertWrapper>
+ </Fragment>
+ }
+ >
+ {t(
+ "You're viewing a shared link. Certain queries and filters have been automatically filled from URL parameters."
+ )}
</Alert>
);
}
-const AlertWrapper = styled('div')`
- display: flex;
-`;
-
-const AlertText = styled('div')`
- flex: 1;
- line-height: 22px;
-`;
-
const RevertButton = styled(Button)`
display: flex;
font-weight: bold;
diff --git a/static/app/components/stream/processingIssueHint.tsx b/static/app/components/stream/processingIssueHint.tsx
index cd004bc5d2e1d8..87899190f83f87 100644
--- a/static/app/components/stream/processingIssueHint.tsx
+++ b/static/app/components/stream/processingIssueHint.tsx
@@ -69,19 +69,18 @@ function ProcessingIssueHint({orgId, projectId, issue, showProject}: Props) {
}
return (
- <StyledAlert type={alertType} showIcon>
- <Wrapper>
- <div>
- {project} <strong>{text}</strong> {lastEvent}
- </div>
- {showButton && (
- <div>
- <StyledButton size="xsmall" to={link}>
- {t('Show details')}
- </StyledButton>
- </div>
- )}
- </Wrapper>
+ <StyledAlert
+ type={alertType}
+ showIcon
+ trailingItems={
+ showButton && (
+ <StyledButton size="xsmall" to={link}>
+ {t('Show details')}
+ </StyledButton>
+ )
+ }
+ >
+ {project} <strong>{text}</strong> {lastEvent}
</StyledAlert>
);
}
@@ -95,11 +94,6 @@ const StyledAlert = styled(Alert)`
font-size: ${p => p.theme.fontSizeMedium};
`;
-const Wrapper = styled('div')`
- display: flex;
- justify-content: space-between;
-`;
-
const StyledButton = styled(Button)`
white-space: nowrap;
margin-left: ${space(1)};
diff --git a/static/app/views/alerts/rules/details/relatedIssuesNotAvailable.tsx b/static/app/views/alerts/rules/details/relatedIssuesNotAvailable.tsx
index 4ba645eefb728b..394d9d4e3a4642 100644
--- a/static/app/views/alerts/rules/details/relatedIssuesNotAvailable.tsx
+++ b/static/app/views/alerts/rules/details/relatedIssuesNotAvailable.tsx
@@ -6,8 +6,6 @@ import Alert from 'sentry/components/alert';
import Button from 'sentry/components/button';
import Link from 'sentry/components/links/link';
import {Panel} from 'sentry/components/panels';
-import {IconInfo} from 'sentry/icons';
-import space from 'sentry/styles/space';
type Props = {
buttonText: string;
@@ -21,18 +19,20 @@ export const RELATED_ISSUES_BOOLEAN_QUERY_ERROR =
* Renders an Alert box of type "info" for boolean queries in alert details. Renders a discover link if the feature is available.
*/
export const RelatedIssuesNotAvailable = ({buttonTo, buttonText}: Props) => (
- <StyledAlert type="info">
- <Content>
- <IconInfo size="lg" />
- <div data-test-id="loading-error-message">
- Related Issues unavailable for this alert.
- </div>
+ <StyledAlert
+ type="info"
+ showIcon
+ trailingItems={
<Feature features={['discover-basic']}>
- <Button type="button" priority="default" size="small" to={buttonTo}>
+ <Button type="button" priority="default" size="xsmall" to={buttonTo}>
{buttonText}
</Button>
</Feature>
- </Content>
+ }
+ >
+ <div data-test-id="loading-error-message">
+ Related Issues unavailable for this alert.
+ </div>
</StyledAlert>
);
@@ -42,10 +42,3 @@ const StyledAlert = styled(Alert)`
border-width: 1px 0;
}
`;
-
-const Content = styled('div')`
- display: grid;
- gap: ${space(1)};
- grid-template-columns: min-content auto max-content;
- align-items: center;
-`;
diff --git a/static/app/views/app/alertMessage.tsx b/static/app/views/app/alertMessage.tsx
index d0f4d0e3e0cacb..64bf2ecde16346 100644
--- a/static/app/views/app/alertMessage.tsx
+++ b/static/app/views/app/alertMessage.tsx
@@ -21,17 +21,22 @@ const AlertMessage = ({alert, system}: Props) => {
const {url, message, type, opaque} = alert;
return (
- <StyledAlert type={type} showIcon system={system} opaque={opaque}>
- <StyledMessage>
- {url ? <ExternalLink href={url}>{message}</ExternalLink> : message}
- </StyledMessage>
- <StyledCloseButton
- icon={<IconClose size="sm" />}
- aria-label={t('Close')}
- onClick={alert.onClose ?? handleClose}
- size="zero"
- borderless
- />
+ <StyledAlert
+ type={type}
+ showIcon
+ system={system}
+ opaque={opaque}
+ trailingItems={
+ <StyledCloseButton
+ icon={<IconClose size="sm" />}
+ aria-label={t('Close')}
+ onClick={alert.onClose ?? handleClose}
+ size="zero"
+ borderless
+ />
+ }
+ >
+ {url ? <ExternalLink href={url}>{message}</ExternalLink> : message}
</StyledAlert>
);
};
@@ -43,18 +48,9 @@ const StyledAlert = styled(Alert)`
margin: 0;
`;
-const StyledMessage = styled('span')`
- display: block;
- margin: auto ${space(4)} auto 0;
-`;
-
const StyledCloseButton = styled(Button)`
background-color: transparent;
transition: opacity 0.1s linear;
- position: absolute;
- top: 50%;
- right: 0;
- transform: translateY(-50%);
&:hover,
&:focus {
diff --git a/static/app/views/organizationGroupDetails/quickTrace/issueQuickTrace.tsx b/static/app/views/organizationGroupDetails/quickTrace/issueQuickTrace.tsx
index 24e798b5959bc0..5a82449ff49802 100644
--- a/static/app/views/organizationGroupDetails/quickTrace/issueQuickTrace.tsx
+++ b/static/app/views/organizationGroupDetails/quickTrace/issueQuickTrace.tsx
@@ -115,16 +115,10 @@ class IssueQuickTrace extends Component<Props, State> {
}
return (
- <StyledAlert type="info" showIcon>
- <AlertContent>
- {tct('The [type] for this error cannot be found. [link]', {
- type: type === 'missing' ? t('transaction') : t('trace'),
- link: (
- <ExternalLink href="https://docs.sentry.io/product/sentry-basics/tracing/trace-view/#troubleshooting">
- {t('Read the docs to understand why.')}
- </ExternalLink>
- ),
- })}
+ <StyledAlert
+ type="info"
+ showIcon
+ trailingItems={
<Button
priority="link"
size="zero"
@@ -133,7 +127,16 @@ class IssueQuickTrace extends Component<Props, State> {
>
<IconClose />
</Button>
- </AlertContent>
+ }
+ >
+ {tct('The [type] for this error cannot be found. [link]', {
+ type: type === 'missing' ? t('transaction') : t('trace'),
+ link: (
+ <ExternalLink href="https://docs.sentry.io/product/sentry-basics/tracing/trace-view/#troubleshooting">
+ {t('Read the docs to understand why.')}
+ </ExternalLink>
+ ),
+ })}
</StyledAlert>
);
}
@@ -195,13 +198,4 @@ const StyledAlert = styled(Alert)`
margin: 0;
`;
-const AlertContent = styled('div')`
- display: flex;
- flex-wrap: wrap;
-
- @media (min-width: ${p => p.theme.breakpoints[0]}) {
- justify-content: space-between;
- }
-`;
-
export default withApi(IssueQuickTrace);
diff --git a/static/app/views/organizationIntegrations/integrationRow.tsx b/static/app/views/organizationIntegrations/integrationRow.tsx
index 00402e6e2c0b8e..6e204f342c1892 100644
--- a/static/app/views/organizationIntegrations/integrationRow.tsx
+++ b/static/app/views/organizationIntegrations/integrationRow.tsx
@@ -118,21 +118,26 @@ const IntegrationRow = (props: Props) => {
</FlexContainer>
{alertText && (
<AlertContainer>
- <Alert type="warning" showIcon>
- <span>{alertText}</span>
- <ResolveNowButton
- href={`${baseUrl}?tab=configurations&referrer=directory_resolve_now`}
- size="xsmall"
- onClick={() =>
- trackIntegrationAnalytics('integrations.resolve_now_clicked', {
- integration_type: convertIntegrationTypeToSnakeCase(type),
- integration: slug,
- organization,
- })
- }
- >
- {resolveText || t('Resolve Now')}
- </ResolveNowButton>
+ <Alert
+ type="warning"
+ showIcon
+ trailingItems={
+ <ResolveNowButton
+ href={`${baseUrl}?tab=configurations&referrer=directory_resolve_now`}
+ size="xsmall"
+ onClick={() =>
+ trackIntegrationAnalytics('integrations.resolve_now_clicked', {
+ integration_type: convertIntegrationTypeToSnakeCase(type),
+ integration: slug,
+ organization,
+ })
+ }
+ >
+ {resolveText || t('Resolve Now')}
+ </ResolveNowButton>
+ }
+ >
+ {alertText}
</Alert>
</AlertContainer>
)}
diff --git a/static/app/views/organizationIntegrations/pluginDeprecationAlert.tsx b/static/app/views/organizationIntegrations/pluginDeprecationAlert.tsx
index c8061ad5a072f6..bc707ca8cf2018 100644
--- a/static/app/views/organizationIntegrations/pluginDeprecationAlert.tsx
+++ b/static/app/views/organizationIntegrations/pluginDeprecationAlert.tsx
@@ -29,21 +29,26 @@ class PluginDeprecationAlert extends Component<Props, State> {
}referrer=directory_upgrade_now`;
return (
<div>
- <Alert type="warning" showIcon>
- <span>{`This integration is being deprecated on ${plugin.deprecationDate}. Please upgrade to avoid any disruption.`}</span>
- <UpgradeNowButton
- href={`${upgradeUrl}${queryParams}`}
- size="xsmall"
- onClick={() =>
- trackIntegrationAnalytics('integrations.resolve_now_clicked', {
- integration_type: 'plugin',
- integration: plugin.slug,
- organization,
- })
- }
- >
- {t('Upgrade Now')}
- </UpgradeNowButton>
+ <Alert
+ type="warning"
+ showIcon
+ trailingItems={
+ <UpgradeNowButton
+ href={`${upgradeUrl}${queryParams}`}
+ size="xsmall"
+ onClick={() =>
+ trackIntegrationAnalytics('integrations.resolve_now_clicked', {
+ integration_type: 'plugin',
+ integration: plugin.slug,
+ organization,
+ })
+ }
+ >
+ {t('Upgrade Now')}
+ </UpgradeNowButton>
+ }
+ >
+ {`This integration is being deprecated on ${plugin.deprecationDate}. Please upgrade to avoid any disruption.`}
</Alert>
</div>
);
diff --git a/tests/js/spec/components/IssueList.spec.tsx b/tests/js/spec/components/IssueList.spec.tsx
index 401aab5b2943fd..ee74b7c86a0c3d 100644
--- a/tests/js/spec/components/IssueList.spec.tsx
+++ b/tests/js/spec/components/IssueList.spec.tsx
@@ -48,7 +48,7 @@ describe('IssueList', () => {
/>
);
- expect(screen.getByTestId('loading-error-message')).toBeInTheDocument();
+ expect(screen.getByText('There was an error loading data.')).toBeInTheDocument();
});
it('refetches data on click from error state', async () => {
@@ -72,7 +72,9 @@ describe('IssueList', () => {
/>
);
- expect(await screen.findByTestId('loading-error-message')).toBeInTheDocument();
+ expect(
+ await screen.findByText('There was an error loading data.')
+ ).toBeInTheDocument();
userEvent.click(screen.getByText('Retry'));
diff --git a/tests/js/spec/components/asyncComponent.spec.jsx b/tests/js/spec/components/asyncComponent.spec.jsx
index 12a65cffd61697..8091b5aebf1962 100644
--- a/tests/js/spec/components/asyncComponent.spec.jsx
+++ b/tests/js/spec/components/asyncComponent.spec.jsx
@@ -93,12 +93,9 @@ describe('AsyncComponent', function () {
render(<UniqueErrorsAsyncComponent />);
- expect(screen.getByTestId('loading-error-message')).toHaveTextContent(
- 'oops there was a problem'
- );
- expect(screen.getByTestId('loading-error-message')).toHaveTextContent(
- 'oops there was a different problem'
- );
+ expect(
+ screen.getByText('oops there was a problem oops there was a different problem')
+ ).toBeInTheDocument();
});
describe('multi-route component', () => {
diff --git a/tests/js/spec/views/settings/projectGeneralSettings.spec.jsx b/tests/js/spec/views/settings/projectGeneralSettings.spec.jsx
index c514c6eb1c3aa4..7f7e32b238dea9 100644
--- a/tests/js/spec/views/settings/projectGeneralSettings.spec.jsx
+++ b/tests/js/spec/views/settings/projectGeneralSettings.spec.jsx
@@ -320,7 +320,7 @@ describe('projectGeneralSettings', function () {
// Slug does not save on blur
expect(putMock).not.toHaveBeenCalled();
- wrapper.find('MessageAndActions button[aria-label="Save"]').simulate('click');
+ wrapper.find('Alert button[aria-label="Save"]').simulate('click');
// fetches new slug
const newProjectGet = MockApiClient.addMockResponse({
@@ -385,9 +385,7 @@ describe('projectGeneralSettings', function () {
wrapper.update();
// Initially does not have "Cancel" button
- expect(wrapper.find('MessageAndActions button[aria-label="Cancel"]')).toHaveLength(
- 0
- );
+ expect(wrapper.find('Alert button[aria-label="Cancel"]')).toHaveLength(0);
// Has initial value
expect(wrapper.find('input[name="resolveAge"]').prop('value')).toBe(19);
@@ -400,18 +398,14 @@ describe('projectGeneralSettings', function () {
// Has updated value
expect(wrapper.find('input[name="resolveAge"]').prop('value')).toBe(12);
// Has "Cancel" button visible
- expect(wrapper.find('MessageAndActions button[aria-label="Cancel"]')).toHaveLength(
- 1
- );
+ expect(wrapper.find('Alert button[aria-label="Cancel"]')).toHaveLength(1);
// Click cancel
- wrapper.find('MessageAndActions button[aria-label="Cancel"]').simulate('click');
+ wrapper.find('Alert button[aria-label="Cancel"]').simulate('click');
wrapper.update();
// Cancel row should disappear
- expect(wrapper.find('MessageAndActions button[aria-label="Cancel"]')).toHaveLength(
- 0
- );
+ expect(wrapper.find('Alert button[aria-label="Cancel"]')).toHaveLength(0);
// Value should be reverted
expect(wrapper.find('input[name="resolveAge"]').prop('value')).toBe(19);
// PUT should not be called
@@ -424,7 +418,7 @@ describe('projectGeneralSettings', function () {
wrapper.update();
// Initially does not have "Save" button
- expect(wrapper.find('MessageAndActions button[aria-label="Save"]')).toHaveLength(0);
+ expect(wrapper.find('Alert button[aria-label="Save"]')).toHaveLength(0);
// Change value
wrapper
@@ -435,13 +429,13 @@ describe('projectGeneralSettings', function () {
wrapper.update();
// Has "Save" button visible
- expect(wrapper.find('MessageAndActions button[aria-label="Save"]')).toHaveLength(1);
+ expect(wrapper.find('Alert button[aria-label="Save"]')).toHaveLength(1);
// Should not have put mock called yet
expect(putMock).not.toHaveBeenCalled();
// Click "Save"
- wrapper.find('MessageAndActions button[aria-label="Save"]').simulate('click');
+ wrapper.find('Alert button[aria-label="Save"]').simulate('click');
await tick();
wrapper.update();
@@ -459,7 +453,7 @@ describe('projectGeneralSettings', function () {
await act(tick);
wrapper.update();
- expect(wrapper.find('MessageAndActions button[aria-label="Save"]')).toHaveLength(0);
+ expect(wrapper.find('Alert button[aria-label="Save"]')).toHaveLength(0);
});
});
});
|
b079ebd6fe579f95bb55896b15e9300ed96d8bd8
|
2025-02-11 02:34:45
|
anthony sottile
|
ref: fix typing for team_details endpoint (#84896)
| false
|
fix typing for team_details endpoint (#84896)
|
ref
|
diff --git a/pyproject.toml b/pyproject.toml
index f639410de300bf..8712fcb86ddbdd 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -135,7 +135,6 @@ module = [
"sentry.api.endpoints.project_release_files",
"sentry.api.endpoints.project_repo_path_parsing",
"sentry.api.endpoints.project_rules_configuration",
- "sentry.api.endpoints.team_details",
"sentry.api.endpoints.user_subscriptions",
"sentry.api.invite_helper",
"sentry.api.paginator",
diff --git a/src/sentry/api/endpoints/team_details.py b/src/sentry/api/endpoints/team_details.py
index 158720816c691b..b7c83de03ed65b 100644
--- a/src/sentry/api/endpoints/team_details.py
+++ b/src/sentry/api/endpoints/team_details.py
@@ -39,7 +39,8 @@ class Meta:
model = Team
fields = ("name", "slug")
- def validate_slug(self, value):
+ def validate_slug(self, value: str) -> str:
+ assert self.instance is not None
qs = Team.objects.filter(slug=value, organization=self.instance.organization).exclude(
id=self.instance.id
)
|
31fc9810320595768bec5ebdd802aba9525bd3df
|
2019-01-04 22:55:15
|
Evan Purkhiser
|
fix(locale): Use 'language code' for locale file names (#11354)
| false
|
Use 'language code' for locale file names (#11354)
|
fix
|
diff --git a/webpack.config.js b/webpack.config.js
index 7a43ce60466d12..178a059e525223 100644
--- a/webpack.config.js
+++ b/webpack.config.js
@@ -72,12 +72,17 @@ const localeCatalogPath = path.join(
const localeCatalog = JSON.parse(fs.readFileSync(localeCatalogPath, 'utf8'));
-// moment uses a lowercase IETF language tag, while django uses the underscore
-// with uppercase syntax
-const normalizeLocale = locale => locale.toLowerCase().replace('_', '-');
+// Translates a locale name to a language code.
+//
+// * po files are kept in a directory represented by the locale name [0]
+// * moment.js locales are stored as language code files
+// * Sentry will request the user configured language from locale/{language}.js
+//
+// [0] https://docs.djangoproject.com/en/2.1/topics/i18n/#term-locale-name
+const localeToLanguage = locale => locale.toLowerCase().replace('_', '-');
const supportedLocales = localeCatalog.supported_locales;
-const normalizedSuppotedLocales = supportedLocales.map(normalizeLocale);
+const supportedLanguages = supportedLocales.map(localeToLanguage);
// A mapping of chunk groups used for locale code splitting
const localeChunkGroups = {};
@@ -85,13 +90,13 @@ const localeChunkGroups = {};
// No need to split the english locale out as it will be completely empty and
// is not included in the django layout.html.
supportedLocales.filter(l => l !== 'en').forEach(locale => {
- const normalizedLocale = normalizeLocale(locale);
- const group = `locale/${locale}`;
+ const language = localeToLanguage(locale);
+ const group = `locale/${language}`;
// List of module path tests to group into locale chunks
const localeGroupTests = [
new RegExp(`locale\\/${locale}\\/.*\\.po$`),
- new RegExp(`moment\\/locale\\/${normalizedLocale}\\.js$`),
+ new RegExp(`moment\\/locale\\/${language}\\.js$`),
];
// module test taken from [0] and modified to support testing against
@@ -127,7 +132,7 @@ const localeRestrictionPlugins = [
),
new webpack.ContextReplacementPlugin(
/moment\/locale/,
- new RegExp(`(${normalizedSuppotedLocales.join('|')})\\.js$`)
+ new RegExp(`(${supportedLanguages.join('|')})\\.js$`)
),
];
|
374036ad70d5839cd717caa9c7cdd7d5c2f9f7fb
|
2019-11-19 00:03:58
|
Lyn Nagara
|
feat: Add Discover name to column mappings (#15616)
| false
|
Add Discover name to column mappings (#15616)
|
feat
|
diff --git a/src/sentry/eventstore/base.py b/src/sentry/eventstore/base.py
index e11346be289ff1..387627c8a5be7a 100644
--- a/src/sentry/eventstore/base.py
+++ b/src/sentry/eventstore/base.py
@@ -6,76 +6,107 @@
from sentry import nodestore
from sentry.utils.services import Service
-Column = namedtuple("Column", "event_name transaction_name alias")
+Column = namedtuple("Column", "event_name transaction_name discover_name alias")
class Columns(Enum):
"""
- Value is a tuple of (internal Events name, internal Transaction name, external alias)
+ Value is a tuple of (internal Events name, internal Transaction name, internal
+ Discover name, external alias)
None means the column is not available in that dataset.
"""
- EVENT_ID = Column("event_id", "event_id", "id")
- GROUP_ID = Column("group_id", None, "issue.id")
- ISSUE = Column("issue", None, "issue.id")
- PROJECT_ID = Column("project_id", "project_id", "project.id")
- TIMESTAMP = Column("timestamp", "finish_ts", "timestamp")
- TIME = Column("time", "bucketed_end", "time")
- CULPRIT = Column("culprit", None, "culprit")
- LOCATION = Column("location", None, "location")
- MESSAGE = Column("message", "transaction_name", "message")
- PLATFORM = Column("platform", "platform", "platform.name")
- ENVIRONMENT = Column("environment", "environment", "environment")
- RELEASE = Column("tags[sentry:release]", "release", "release")
- TITLE = Column("title", "transaction_name", "title")
- TYPE = Column("type", None, "event.type")
- TAGS_KEY = Column("tags.key", "tags.key", "tags.key")
- TAGS_VALUE = Column("tags.value", "tags.value", "tags.value")
- TAGS_KEYS = Column("tags_key", "tags_key", "tags_key")
- TAGS_VALUES = Column("tags_value", "tags_value", "tags_value")
- TRANSACTION = Column("transaction", "transaction_name", "transaction")
- USER = Column("tags[sentry:user]", "user", "user")
- USER_ID = Column("user_id", "user_id", "user.id")
- USER_EMAIL = Column("email", "user_email", "user.email")
- USER_USERNAME = Column("username", "user_name", "user.username")
- USER_IP_ADDRESS = Column("ip_address", "ip_address_v4", "user.ip")
- SDK_NAME = Column("sdk_name", None, "sdk.name")
- SDK_VERSION = Column("sdk_version", None, "sdk.version")
- HTTP_METHOD = Column("http_method", None, "http.method")
- HTTP_REFERER = Column("http_referer", None, "http.url")
- OS_BUILD = Column("os_build", None, "os.build")
- OS_KERNEL_VERSION = Column("os_kernel_version", None, "os.kernel_version")
- DEVICE_NAME = Column("device_name", None, "device.name")
- DEVICE_BRAND = Column("device_brand", None, "device.brand")
- DEVICE_LOCALE = Column("device_locale", None, "device.locale")
- DEVICE_UUID = Column("device_uuid", None, "device.uuid")
- DEVICE_ARCH = Column("device_arch", None, "device.arch")
- DEVICE_BATTERY_LEVEL = Column("device_battery_level", None, "device.battery_level")
- DEVICE_ORIENTATION = Column("device_orientation", None, "device.orientation")
- DEVICE_SIMULATOR = Column("device_simulator", None, "device.simulator")
- DEVICE_ONLINE = Column("device_online", None, "device.online")
- DEVICE_CHARGING = Column("device_charging", None, "device.charging")
- GEO_COUNTRY_CODE = Column("geo_country_code", None, "geo.country_code")
- GEO_REGION = Column("geo_region", None, "geo.region")
- GEO_CITY = Column("geo_city", None, "geo.city")
- ERROR_TYPE = Column("exception_stacks.type", None, "error.type")
- ERROR_VALUE = Column("exception_stacks.value", None, "error.value")
- ERROR_MECHANISM = Column("exception_stacks.mechanism_type", None, "error.mechanism")
- ERROR_HANDLED = Column("exception_stacks.mechanism_handled", None, "error.handled")
- STACK_ABS_PATH = Column("exception_frames.abs_path", None, "stack.abs_path")
- STACK_FILENAME = Column("exception_frames.filename", None, "stack.filename")
- STACK_PACKAGE = Column("exception_frames.package", None, "stack.package")
- STACK_MODULE = Column("exception_frames.module", None, "stack.module")
- STACK_FUNCTION = Column("exception_frames.function", None, "stack.function")
- STACK_IN_APP = Column("exception_frames.in_app", None, "stack.in_app")
- STACK_COLNO = Column("exception_frames.colno", None, "stack.colno")
- STACK_LINENO = Column("exception_frames.lineno", None, "stack.lineno")
- STACK_STACK_LEVEL = Column("exception_frames.stack_level", None, "stack.stack_level")
- CONTEXTS_KEY = Column("contexts.key", "contexts.key", "contexts.key")
- CONTEXTS_VALUE = Column("contexts.value", "contexts.value", "contexts.value")
+ EVENT_ID = Column("event_id", "event_id", "event_id", "id")
+ GROUP_ID = Column("group_id", None, "group_id", "issue.id")
+ ISSUE = Column("issue", None, "group_id", "issue.id")
+ PROJECT_ID = Column("project_id", "project_id", "project_id", "project.id")
+ TIMESTAMP = Column("timestamp", "finish_ts", "timestamp", "timestamp")
+ TIME = Column("time", "bucketed_end", "time", "time")
+ CULPRIT = Column("culprit", None, "culprit", "culprit")
+ LOCATION = Column("location", None, "location", "location")
+ MESSAGE = Column("message", "transaction_name", "message", "message")
+ PLATFORM = Column("platform", "platform", "platform", "platform.name")
+ ENVIRONMENT = Column("environment", "environment", "environment", "environment")
+ RELEASE = Column("tags[sentry:release]", "release", "release", "release")
+ TITLE = Column("title", "transaction_name", "title", "title")
+ TYPE = Column("type", None, "type", "event.type")
+ TAGS_KEY = Column("tags.key", "tags.key", "tags.key", "tags.key")
+ TAGS_VALUE = Column("tags.value", "tags.value", "tags.value", "tags.value")
+ TAGS_KEYS = Column("tags_key", "tags_key", "tags_key", "tags_key")
+ TAGS_VALUES = Column("tags_value", "tags_value", "tags_value", "tags_value")
+ TRANSACTION = Column("transaction", "transaction_name", "transaction", "transaction")
+ USER = Column("tags[sentry:user]", "user", "user", "user")
+ USER_ID = Column("user_id", "user_id", "user_id", "user.id")
+ USER_EMAIL = Column("email", "user_email", "email", "user.email")
+ USER_USERNAME = Column("username", "user_name", "username", "user.username")
+ USER_IP_ADDRESS = Column("ip_address", "ip_address_v4", "ip_address", "user.ip")
+ SDK_NAME = Column("sdk_name", None, "sdk_name", "sdk.name")
+ SDK_VERSION = Column("sdk_version", None, "sdk_version", "sdk.version")
+ HTTP_METHOD = Column("http_method", None, "http_method", "http.method")
+ HTTP_REFERER = Column("http_referer", None, "http_referer", "http.url")
+ OS_BUILD = Column("os_build", None, "os_build", "os.build")
+ OS_KERNEL_VERSION = Column("os_kernel_version", None, "os_kernel_version", "os.kernel_version")
+ DEVICE_NAME = Column("device_name", None, "device_name", "device.name")
+ DEVICE_BRAND = Column("device_brand", None, "device_brand", "device.brand")
+ DEVICE_LOCALE = Column("device_locale", None, "device_locale", "device.locale")
+ DEVICE_UUID = Column("device_uuid", None, "device_uuid", "device.uuid")
+ DEVICE_ARCH = Column("device_arch", None, "device_arch", "device.arch")
+ DEVICE_BATTERY_LEVEL = Column(
+ "device_battery_level", None, "device_battery_level", "device.battery_level"
+ )
+ DEVICE_ORIENTATION = Column(
+ "device_orientation", None, "device_orientation", "device.orientation"
+ )
+ DEVICE_SIMULATOR = Column("device_simulator", None, "device_simulator", "device.simulator")
+ DEVICE_ONLINE = Column("device_online", None, "device_online", "device.online")
+ DEVICE_CHARGING = Column("device_charging", None, "device_charging", "device.charging")
+ GEO_COUNTRY_CODE = Column("geo_country_code", None, "geo_country_code", "geo.country_code")
+ GEO_REGION = Column("geo_region", None, "geo_region", "geo.region")
+ GEO_CITY = Column("geo_city", None, "geo_city", "geo.city")
+ ERROR_TYPE = Column("exception_stacks.type", None, "exception_stacks.type", "error.type")
+ ERROR_VALUE = Column("exception_stacks.value", None, "exception_stacks.value", "error.value")
+ ERROR_MECHANISM = Column(
+ "exception_stacks.mechanism_type",
+ None,
+ "exception_stacks.mechanism_type",
+ "error.mechanism",
+ )
+ ERROR_HANDLED = Column(
+ "exception_stacks.mechanism_handled",
+ None,
+ "exception_stacks.mechanism_handled",
+ "error.handled",
+ )
+ STACK_ABS_PATH = Column(
+ "exception_frames.abs_path", None, "exception_frames.abs_path", "stack.abs_path"
+ )
+ STACK_FILENAME = Column(
+ "exception_frames.filename", None, "exception_frames.filename", "stack.filename"
+ )
+ STACK_PACKAGE = Column(
+ "exception_frames.package", None, "exception_frames.package", "stack.package"
+ )
+ STACK_MODULE = Column(
+ "exception_frames.module", None, "exception_frames.module", "stack.module"
+ )
+ STACK_FUNCTION = Column(
+ "exception_frames.function", None, "exception_frames.function", "stack.function"
+ )
+ STACK_IN_APP = Column(
+ "exception_frames.in_app", None, "exception_frames.in_app", "stack.in_app"
+ )
+ STACK_COLNO = Column("exception_frames.colno", None, "exception_frames.colno", "stack.colno")
+ STACK_LINENO = Column(
+ "exception_frames.lineno", None, "exception_frames.lineno", "stack.lineno"
+ )
+ STACK_STACK_LEVEL = Column(
+ "exception_frames.stack_level", None, "exception_frames.stack_level", "stack.stack_level"
+ )
+ CONTEXTS_KEY = Column("contexts.key", "contexts.key", "contexts.key", "contexts.key")
+ CONTEXTS_VALUE = Column("contexts.value", "contexts.value", "contexts.value", "contexts.value")
# Transactions specific columns
- TRANSACTION_OP = Column(None, "transaction_op", "transaction.op")
- TRANSACTION_DURATION = Column(None, "duration", "transaction.duration")
+ TRANSACTION_OP = Column(None, "transaction_op", "transaction_op", "transaction.op")
+ TRANSACTION_DURATION = Column(None, "duration", "duration", "transaction.duration")
def get_columns_from_aliases(aliases):
|
a9991129f8aa87eeeac302eaea9fb65cdc049c9e
|
2019-04-25 02:14:59
|
Lyn Nagara
|
feat(incidents): Add container component for incidents (#12917)
| false
|
Add container component for incidents (#12917)
|
feat
|
diff --git a/src/sentry/features/__init__.py b/src/sentry/features/__init__.py
index f1e35e5f417067..35e81bcd0fd8b0 100644
--- a/src/sentry/features/__init__.py
+++ b/src/sentry/features/__init__.py
@@ -65,6 +65,7 @@
default_manager.add('organizations:integrations-issue-basic', OrganizationFeature) # NOQA
default_manager.add('organizations:integrations-issue-sync', OrganizationFeature) # NOQA
default_manager.add('organizations:internal-catchall', OrganizationFeature) # NOQA
+default_manager.add('organizations:incidents', OrganizationFeature) # NOQA
default_manager.add('organizations:sentry-apps', OrganizationFeature) # NOQA
default_manager.add('organizations:invite-members', OrganizationFeature) # NOQA
default_manager.add('organizations:large-debug-files', OrganizationFeature) # NOQA
diff --git a/src/sentry/static/sentry/app/routes.jsx b/src/sentry/static/sentry/app/routes.jsx
index 8afd0350ffa97c..bcb8f1f2bdf10a 100644
--- a/src/sentry/static/sentry/app/routes.jsx
+++ b/src/sentry/static/sentry/app/routes.jsx
@@ -908,6 +908,21 @@ function routes() {
component={errorHandler(LazyLoad)}
/>
</Route>
+ <Route
+ path="/organizations/:orgId/incidents/"
+ componentPromise={() =>
+ import(/* webpackChunkName: "OrganizationIncidentsContainer" */ './views/organizationIncidents')
+ }
+ component={errorHandler(LazyLoad)}
+ >
+ <IndexRoute
+ componentPromise={() =>
+ import(/* webpackChunkName: "OrganizationIncidents" */ './views/organizationIncidents/list')
+ }
+ component={errorHandler(LazyLoad)}
+ />
+ </Route>
+
<Route
path="/organizations/:orgId/projects/:projectId/getting-started/"
component={errorHandler(ProjectGettingStarted)}
diff --git a/src/sentry/static/sentry/app/views/organizationIncidents/index.jsx b/src/sentry/static/sentry/app/views/organizationIncidents/index.jsx
new file mode 100644
index 00000000000000..9a75a88c68610d
--- /dev/null
+++ b/src/sentry/static/sentry/app/views/organizationIncidents/index.jsx
@@ -0,0 +1,43 @@
+import React from 'react';
+
+import SentryTypes from 'app/sentryTypes';
+import Feature from 'app/components/acl/feature';
+import Alert from 'app/components/alert';
+import withOrganization from 'app/utils/withOrganization';
+import {t} from 'app/locale';
+import {PageContent, PageHeader} from 'app/styles/organization';
+import PageHeading from 'app/components/pageHeading';
+import BetaTag from 'app/components/betaTag';
+
+class OrganizationIncidentsContainer extends React.Component {
+ static propTypes = {
+ organization: SentryTypes.Organization.isRequired,
+ };
+
+ renderNoAccess() {
+ return <Alert type="warning">{t("You don't have access to this feature")}</Alert>;
+ }
+
+ render() {
+ const {organization, children} = this.props;
+
+ return (
+ <PageContent>
+ <Feature
+ features={['organizations:incidents']}
+ organization={organization}
+ renderDisabled={this.renderNoAccess}
+ >
+ <PageHeader>
+ <PageHeading withMargins>
+ {t('Incidents')} <BetaTag />
+ </PageHeading>
+ </PageHeader>
+ {children}
+ </Feature>
+ </PageContent>
+ );
+ }
+}
+
+export default withOrganization(OrganizationIncidentsContainer);
diff --git a/src/sentry/static/sentry/app/views/organizationIncidents/list/index.jsx b/src/sentry/static/sentry/app/views/organizationIncidents/list/index.jsx
new file mode 100644
index 00000000000000..aa6a422e268234
--- /dev/null
+++ b/src/sentry/static/sentry/app/views/organizationIncidents/list/index.jsx
@@ -0,0 +1,7 @@
+import React from 'react';
+
+export default class OrganizationIncidents extends React.Component {
+ render() {
+ return <div />;
+ }
+}
diff --git a/tests/js/spec/views/organizationIncidents/index.spec.jsx b/tests/js/spec/views/organizationIncidents/index.spec.jsx
new file mode 100644
index 00000000000000..5dc59adb14b57b
--- /dev/null
+++ b/tests/js/spec/views/organizationIncidents/index.spec.jsx
@@ -0,0 +1,17 @@
+import React from 'react';
+import {mount} from 'enzyme';
+
+import OrganizationIncidentsContainer from 'app/views/organizationIncidents/index';
+
+describe('OrganizationIncidentsContainer', function() {
+ describe('no access without feature flag', function() {
+ it('display no access message', async function() {
+ const organization = TestStubs.Organization({projects: [TestStubs.Project()]});
+ const wrapper = mount(
+ <OrganizationIncidentsContainer />,
+ TestStubs.routerContext([{organization}])
+ );
+ expect(wrapper.text()).toBe("You don't have access to this feature");
+ });
+ });
+});
|
81b5b27017435cf2be2d4a901decfe2fb38b0fc9
|
2023-04-06 00:21:33
|
Katie Byers
|
feat(integrations): Add `host` and `path` to `ApiError` (#46953)
| false
|
Add `host` and `path` to `ApiError` (#46953)
|
feat
|
diff --git a/src/sentry/shared_integrations/exceptions/base.py b/src/sentry/shared_integrations/exceptions/base.py
index de64739518906a..5419387bafe4ec 100644
--- a/src/sentry/shared_integrations/exceptions/base.py
+++ b/src/sentry/shared_integrations/exceptions/base.py
@@ -1,6 +1,7 @@
from __future__ import annotations
from typing import Any
+from urllib.parse import urlparse
from bs4 import BeautifulSoup
from requests import Response
@@ -11,13 +12,25 @@
class ApiError(Exception):
code: int | None = None
- def __init__(self, text: str, code: int | None = None, url: str | None = None) -> None:
+ def __init__(
+ self,
+ text: str,
+ code: int | None = None,
+ url: str | None = None,
+ host: str | None = None,
+ path: str | None = None,
+ ) -> None:
if code is not None:
self.code = code
self.text = text
self.url = url
+ # we allow `host` and `path` to be passed in separately from `url` in case
+ # either one is all we have
+ self.host = host
+ self.path = path
self.json: dict[str, Any] | None = None
self.xml: BeautifulSoup | None = None
+
# TODO(dcramer): pull in XML support from Jira
if text:
try:
@@ -26,6 +39,19 @@ def __init__(self, text: str, code: int | None = None, url: str | None = None) -
if self.text[:5] == "<?xml":
# perhaps it's XML?
self.xml = BeautifulSoup(self.text, "xml")
+
+ if url and not self.host:
+ try:
+ self.host = urlparse(url).netloc
+ except ValueError:
+ self.host = "[invalid URL]"
+
+ if url and not self.path:
+ try:
+ self.path = urlparse(url).path
+ except ValueError:
+ self.path = "[invalid URL]"
+
super().__init__(text[:1024])
@classmethod
|
2723902825c6f497d2be1e7ae9b602c5cfed8ba3
|
2025-02-21 14:16:55
|
Ogi
|
fix(demo-mode): use DemoSafePermission class (#85444)
| false
|
use DemoSafePermission class (#85444)
|
fix
|
diff --git a/src/sentry/api/bases/organization.py b/src/sentry/api/bases/organization.py
index 88430bb6b662d7..4cd8d7609c58a7 100644
--- a/src/sentry/api/bases/organization.py
+++ b/src/sentry/api/bases/organization.py
@@ -14,7 +14,7 @@
from sentry.api.base import Endpoint
from sentry.api.exceptions import ResourceDoesNotExist
from sentry.api.helpers.environments import get_environments
-from sentry.api.permissions import SentryPermission, StaffPermissionMixin
+from sentry.api.permissions import DemoSafePermission, StaffPermissionMixin
from sentry.api.utils import get_date_range_from_params, is_member_disabled_from_limit
from sentry.auth.staff import is_active_staff
from sentry.auth.superuser import is_active_superuser
@@ -43,7 +43,7 @@ class NoProjects(Exception):
pass
-class OrganizationPermission(SentryPermission):
+class OrganizationPermission(DemoSafePermission):
scope_map = {
"GET": ["org:read", "org:write", "org:admin"],
"POST": ["org:write", "org:admin"],
diff --git a/src/sentry/api/permissions.py b/src/sentry/api/permissions.py
index d62cdb3cf60f01..edc7410ed61c51 100644
--- a/src/sentry/api/permissions.py
+++ b/src/sentry/api/permissions.py
@@ -3,7 +3,7 @@
from collections.abc import Sequence
from typing import TYPE_CHECKING, Any
-from rest_framework.permissions import BasePermission, IsAuthenticated
+from rest_framework.permissions import SAFE_METHODS, BasePermission, IsAuthenticated
from rest_framework.request import Request
from sentry.api.exceptions import (
@@ -274,6 +274,59 @@ def determine_access(
raise MemberDisabledOverLimit(organization)
+class DemoSafePermission(SentryPermission):
+ """
+ A permission class that extends `SentryPermission` to provide read-only access for users
+ in a demo mode. This class modifies the access control logic to ensure that users identified
+ as read-only can only perform safe operations, such as GET and HEAD requests, on resources.
+ """
+
+ def determine_access(
+ self,
+ request: Request,
+ organization: RpcUserOrganizationContext | Organization | RpcOrganization,
+ ) -> None:
+
+ org_context: RpcUserOrganizationContext | None = None
+ if isinstance(organization, RpcUserOrganizationContext):
+ org_context = organization
+ else:
+ org_context = organization_service.get_organization_by_id(
+ id=extract_id_from(organization), user_id=request.user.id if request.user else None
+ )
+
+ if org_context is None:
+ assert False, "Failed to fetch organization in determine_access"
+
+ if demo_mode.is_demo_user(request.user):
+ if org_context.member and demo_mode.is_demo_mode_enabled():
+ readonly_scopes = demo_mode.get_readonly_scopes()
+ org_context.member.scopes = readonly_scopes
+ request.access = access.from_request_org_and_scopes(
+ request=request,
+ rpc_user_org_context=org_context,
+ scopes=readonly_scopes,
+ )
+
+ return
+
+ return super().determine_access(request, org_context)
+
+ def has_permission(self, request: Request, view: object) -> bool:
+ if demo_mode.is_demo_user(request.user):
+ if not demo_mode.is_demo_mode_enabled() or request.method not in SAFE_METHODS:
+ return False
+
+ return super().has_permission(request, view)
+
+ def has_object_permission(self, request: Request, view: object | None, obj: Any) -> bool:
+ if demo_mode.is_demo_user(request.user):
+ if not demo_mode.is_demo_mode_enabled() or request.method not in SAFE_METHODS:
+ return False
+
+ return super().has_object_permission(request, view, obj)
+
+
class SentryIsAuthenticated(IsAuthenticated):
def has_permission(self, request: Request, view: object) -> bool:
if demo_mode.is_demo_user(request.user):
diff --git a/src/sentry/sentry_apps/api/endpoints/sentry_app_rotate_secret.py b/src/sentry/sentry_apps/api/endpoints/sentry_app_rotate_secret.py
index c53b5504a9bb11..67c534470cb748 100644
--- a/src/sentry/sentry_apps/api/endpoints/sentry_app_rotate_secret.py
+++ b/src/sentry/sentry_apps/api/endpoints/sentry_app_rotate_secret.py
@@ -8,7 +8,7 @@
from sentry.api.api_owners import ApiOwner
from sentry.api.api_publish_status import ApiPublishStatus
from sentry.api.base import control_silo_endpoint
-from sentry.api.permissions import SentryPermission
+from sentry.api.permissions import DemoSafePermission
from sentry.api.serializers import serialize
from sentry.auth.superuser import superuser_has_permission
from sentry.constants import SentryAppStatus
@@ -21,7 +21,7 @@
logger = logging.getLogger(__name__)
-class SentryAppRotateSecretPermission(SentryPermission):
+class SentryAppRotateSecretPermission(DemoSafePermission):
scope_map = {
"POST": ["org:write", "org:admin"],
}
diff --git a/src/sentry/users/api/bases/user.py b/src/sentry/users/api/bases/user.py
index 16a5afb96eacfe..a3b08c82189e59 100644
--- a/src/sentry/users/api/bases/user.py
+++ b/src/sentry/users/api/bases/user.py
@@ -1,81 +1,27 @@
from __future__ import annotations
-from typing import TYPE_CHECKING, Any
+from typing import Any
from django.contrib.auth.models import AnonymousUser
-from rest_framework.permissions import SAFE_METHODS, BasePermission
+from rest_framework.permissions import BasePermission
from rest_framework.request import Request
from sentry.api.base import Endpoint
from sentry.api.exceptions import ResourceDoesNotExist
-from sentry.api.permissions import SentryPermission, StaffPermissionMixin
+from sentry.api.permissions import DemoSafePermission, StaffPermissionMixin
from sentry.auth.services.access.service import access_service
from sentry.auth.superuser import is_active_superuser, superuser_has_permission
from sentry.auth.system import is_system_auth
-from sentry.hybridcloud.rpc import extract_id_from
from sentry.models.organization import OrganizationStatus
from sentry.models.organizationmapping import OrganizationMapping
from sentry.models.organizationmembermapping import OrganizationMemberMapping
-from sentry.organizations.services.organization import (
- RpcOrganization,
- RpcUserOrganizationContext,
- organization_service,
-)
+from sentry.organizations.services.organization import organization_service
from sentry.users.models.user import User
from sentry.users.services.user import RpcUser
from sentry.users.services.user.service import user_service
-from sentry.utils import demo_mode
-if TYPE_CHECKING:
- from sentry.models.organization import Organization
-
-class DemoUserPermission(SentryPermission):
- """
- A permission class that extends `SentryPermission` to provide read-only access for users
- in a demo mode. This class modifies the access control logic to ensure that users identified
- as read-only can only perform safe operations, such as GET and HEAD requests, on resources.
- """
-
- def determine_access(
- self,
- request: Request,
- organization: RpcUserOrganizationContext | Organization | RpcOrganization,
- ) -> None:
-
- org_context: RpcUserOrganizationContext | None
- if isinstance(organization, RpcUserOrganizationContext):
- org_context = organization
- else:
- org_context = organization_service.get_organization_by_id(
- id=extract_id_from(organization), user_id=request.user.id if request.user else None
- )
-
- if org_context is None:
- assert False, "Failed to fetch organization in determine_access"
-
- if demo_mode.is_demo_user(request.user):
- if org_context.member and demo_mode.is_demo_mode_enabled():
- org_context.member.scopes = list(demo_mode.get_readonly_scopes())
-
- return super().determine_access(request, org_context)
-
- def has_permission(self, request: Request, view: object) -> bool:
- if demo_mode.is_demo_user(request.user):
- if not demo_mode.is_demo_mode_enabled() or request.method not in SAFE_METHODS:
- return False
-
- return super().has_permission(request, view)
-
- def has_object_permission(self, request: Request, view: object | None, obj: Any) -> bool:
- if demo_mode.is_demo_user(request.user):
- if not demo_mode.is_demo_mode_enabled() or request.method not in SAFE_METHODS:
- return False
-
- return super().has_object_permission(request, view, obj)
-
-
-class UserPermission(DemoUserPermission):
+class UserPermission(DemoSafePermission):
def has_object_permission(
self, request: Request, view: object | None, user: User | RpcUser | None = None
diff --git a/src/sentry/users/api/endpoints/user_ips.py b/src/sentry/users/api/endpoints/user_ips.py
index d9fb05d7ddb930..b9b3e2f5202e7a 100644
--- a/src/sentry/users/api/endpoints/user_ips.py
+++ b/src/sentry/users/api/endpoints/user_ips.py
@@ -1,3 +1,4 @@
+from rest_framework import status
from rest_framework.request import Request
from rest_framework.response import Response
@@ -10,6 +11,7 @@
from sentry.users.api.serializers.userip import UserIPSerializer
from sentry.users.models.user import User
from sentry.users.models.userip import UserIP
+from sentry.utils.demo_mode import is_demo_user
@control_silo_endpoint
@@ -29,6 +31,9 @@ def get(self, request: Request, user: User) -> Response:
:auth required:
"""
+ if is_demo_user(user):
+ return Response(status=status.HTTP_403_FORBIDDEN)
+
queryset = UserIP.objects.filter(user=user)
return self.paginate(
diff --git a/tests/sentry/api/test_permissions.py b/tests/sentry/api/test_permissions.py
index f67058ca536312..0409931404b8a0 100644
--- a/tests/sentry/api/test_permissions.py
+++ b/tests/sentry/api/test_permissions.py
@@ -1,11 +1,14 @@
from sentry.api.permissions import (
+ DemoSafePermission,
SentryIsAuthenticated,
StaffPermission,
SuperuserOrStaffFeatureFlaggedPermission,
SuperuserPermission,
)
+from sentry.organizations.services.organization import organization_service
from sentry.testutils.cases import DRFPermissionTestCase
from sentry.testutils.helpers.options import override_options
+from sentry.utils.demo_mode import READONLY_SCOPES
class PermissionsTest(DRFPermissionTestCase):
@@ -58,3 +61,114 @@ def test_has_object_permission(self):
assert not self.user_permission.has_object_permission(
self.make_request(self.readonly_user), None, None
)
+
+
+class DemoSafePermissionsTest(DRFPermissionTestCase):
+ user_permission = DemoSafePermission()
+
+ def setUp(self):
+ super().setUp()
+ self.normal_user = self.create_user(
+ id=1,
+ )
+ self.readonly_user = self.create_user(id=2)
+ self.organization = self.create_organization(owner=self.normal_user)
+ self.org_member_scopes = self.create_member(
+ organization_id=self.organization.id, user_id=self.readonly_user.id
+ ).get_scopes()
+
+ def _get_rpc_context(self, user):
+ rpc_context = organization_service.get_organization_by_id(
+ id=self.organization.id, user_id=user.id
+ )
+
+ assert rpc_context
+ return rpc_context
+
+ @override_options({"demo-mode.enabled": True, "demo-mode.users": [2]})
+ def test_safe_methods(self):
+ for method in ("GET", "HEAD", "OPTIONS"):
+ assert self.user_permission.has_permission(
+ self.make_request(self.readonly_user, method=method), None
+ )
+ assert self.user_permission.has_permission(
+ self.make_request(self.normal_user, method=method), None
+ )
+
+ @override_options({"demo-mode.enabled": True, "demo-mode.users": [2]})
+ def test_unsafe_methods(self):
+ for method in ("POST", "PUT", "PATCH", "DELETE"):
+ assert not self.user_permission.has_permission(
+ self.make_request(self.readonly_user, method=method), None
+ )
+ assert self.user_permission.has_permission(
+ self.make_request(self.normal_user, method=method), None
+ )
+
+ @override_options({"demo-mode.enabled": False, "demo-mode.users": [2]})
+ def test_safe_method_demo_mode_disabled(self):
+ for method in ("GET", "HEAD", "OPTIONS"):
+ assert not self.user_permission.has_permission(
+ self.make_request(self.readonly_user, method=method), None
+ )
+ assert self.user_permission.has_permission(
+ self.make_request(self.normal_user, method=method), None
+ )
+
+ @override_options({"demo-mode.enabled": False, "demo-mode.users": [2]})
+ def test_unsafe_methods_demo_mode_disabled(self):
+ for method in ("POST", "PUT", "PATCH", "DELETE"):
+ assert not self.user_permission.has_permission(
+ self.make_request(self.readonly_user, method=method), None
+ )
+ assert self.user_permission.has_permission(
+ self.make_request(self.normal_user, method=method), None
+ )
+
+ @override_options({"demo-mode.enabled": False, "demo-mode.users": [2]})
+ def test_determine_access_disabled(self):
+ self.user_permission.determine_access(
+ request=self.make_request(self.normal_user),
+ organization=self._get_rpc_context(self.normal_user),
+ )
+
+ readonly_rpc_context = self._get_rpc_context(self.readonly_user)
+
+ self.user_permission.determine_access(
+ request=self.make_request(self.readonly_user),
+ organization=readonly_rpc_context,
+ )
+
+ assert readonly_rpc_context.member.scopes == list(self.org_member_scopes)
+
+ @override_options({"demo-mode.enabled": True, "demo-mode.users": [2]})
+ def test_determine_access(self):
+ self.user_permission.determine_access(
+ request=self.make_request(self.normal_user),
+ organization=self._get_rpc_context(self.normal_user),
+ )
+
+ readonly_rpc_context = self._get_rpc_context(self.readonly_user)
+
+ self.user_permission.determine_access(
+ request=self.make_request(self.readonly_user),
+ organization=readonly_rpc_context,
+ )
+
+ assert readonly_rpc_context.member.scopes == READONLY_SCOPES
+
+ @override_options({"demo-mode.enabled": False, "demo-mode.users": []})
+ def test_determine_access_no_demo_users(self):
+ self.user_permission.determine_access(
+ request=self.make_request(self.normal_user),
+ organization=self._get_rpc_context(self.normal_user),
+ )
+
+ readonly_rpc_context = self._get_rpc_context(self.readonly_user)
+
+ self.user_permission.determine_access(
+ request=self.make_request(self.readonly_user),
+ organization=readonly_rpc_context,
+ )
+
+ assert readonly_rpc_context.member.scopes == list(self.org_member_scopes)
diff --git a/tests/sentry/users/api/bases/test_user.py b/tests/sentry/users/api/bases/test_user.py
index 8f04b32cb2e4bb..694bfd5a917357 100644
--- a/tests/sentry/users/api/bases/test_user.py
+++ b/tests/sentry/users/api/bases/test_user.py
@@ -8,7 +8,6 @@
from sentry.testutils.helpers.options import override_options
from sentry.testutils.silo import all_silo_test, control_silo_test, no_silo_test
from sentry.users.api.bases.user import (
- DemoUserPermission,
RegionSiloUserEndpoint,
UserAndStaffPermission,
UserEndpoint,
@@ -131,90 +130,3 @@ class ControlUserEndpointTest(BaseUserEndpointTest):
# TODO(HC): Delete this once region silo by default changes land
class RegionSiloUserEndpointTest(BaseUserEndpointTest):
endpoint = RegionSiloUserEndpoint()
-
-
-@all_silo_test
-class UserDemoModePermissionsTest(DRFPermissionTestCase):
- user_permission = DemoUserPermission()
-
- def setUp(self):
- super().setUp()
- self.normal_user = self.create_user(id=1)
- self.readonly_user = self.create_user(id=2)
-
- @override_options({"demo-mode.enabled": True, "demo-mode.users": [2]})
- def test_readonly_user_has_permission(self):
- assert self.user_permission.has_permission(self.make_request(self.readonly_user), None)
-
- def test_readonly_user_has_object_permission(self):
- assert not self.user_permission.has_object_permission(
- self.make_request(self.readonly_user), None, None
- )
-
- @override_options({"demo-mode.enabled": True, "demo-mode.users": [2]})
- def test_safe_method(self):
- assert self.user_permission.has_permission(
- self.make_request(self.readonly_user, method="GET"), None
- )
- assert self.user_permission.has_permission(
- self.make_request(self.normal_user, method="GET"), None
- )
-
- @override_options({"demo-mode.enabled": True, "demo-mode.users": [2]})
- def test_unsafe_methods(self):
- for method in ("POST", "PUT", "PATCH", "DELETE"):
- assert not self.user_permission.has_permission(
- self.make_request(self.readonly_user, method=method), None
- )
-
- assert self.user_permission.has_permission(
- self.make_request(self.normal_user, method=method), None
- )
-
- @override_options({"demo-mode.enabled": False, "demo-mode.users": [2]})
- def test_safe_method_demo_mode_disabled(self):
- assert not self.user_permission.has_permission(
- self.make_request(self.readonly_user, method="GET"), None
- )
- assert self.user_permission.has_permission(
- self.make_request(self.normal_user, method="GET"), None
- )
-
- @override_options({"demo-mode.enabled": False, "demo-mode.users": [2]})
- def test_unsafe_methods_demo_mode_disabled(self):
- for method in ("POST", "PUT", "PATCH", "DELETE"):
- assert not self.user_permission.has_permission(
- self.make_request(self.readonly_user, method=method), None
- )
-
- assert self.user_permission.has_permission(
- self.make_request(self.normal_user, method=method), None
- )
-
- @override_options({"demo-mode.enabled": True, "demo-mode.users": [2]})
- def test_determine_access(self):
- assert self.user_permission.determine_access(
- self.make_request(self.readonly_user, method="GET"), None
- )
- assert self.user_permission.determine_access(
- self.make_request(self.normal_user, method="GET"), None
- )
-
- @override_options({"demo-mode.enabled": False, "demo-mode.users": [2]})
- def test_determine_access_disabled(self):
- assert not self.user_permission.determine_access(
- self.make_request(self.readonly_user, method="GET"), None
- )
- assert self.user_permission.determine_access(
- self.make_request(self.normal_user, method="GET"), None
- )
-
- @override_options({"demo-mode.enabled": True, "demo-mode.users": [2]})
- def test_determine_access_superuser(self):
- assert not self.user_permission.determine_access(
- self.make_request(self.readonly_user, method="POST"), None
- )
- self.readonly_user.update(is_superuser=True)
- assert self.user_permission.determine_access(
- self.make_request(self.readonly_user, method="POST"), None
- )
diff --git a/tests/sentry/users/api/endpoints/test_user_ips.py b/tests/sentry/users/api/endpoints/test_user_ips.py
index 22fc67123a50d5..181a5ce9be1153 100644
--- a/tests/sentry/users/api/endpoints/test_user_ips.py
+++ b/tests/sentry/users/api/endpoints/test_user_ips.py
@@ -1,16 +1,18 @@
from datetime import datetime, timezone
from sentry.testutils.cases import APITestCase
+from sentry.testutils.helpers.options import override_options
from sentry.testutils.silo import control_silo_test
from sentry.users.models.userip import UserIP
@control_silo_test
-class UserEmailsTest(APITestCase):
+class UserIPsTest(APITestCase):
endpoint = "sentry-api-0-user-ips"
def setUp(self):
super().setUp()
+ self.user = self.create_user(id=1)
self.login_as(self.user)
def test_simple(self):
@@ -34,3 +36,8 @@ def test_simple(self):
assert response.data[0]["ipAddress"] == "127.0.0.1"
assert response.data[1]["ipAddress"] == "127.0.0.2"
+
+ @override_options({"demo-mode.enabled": True, "demo-mode.users": [1]})
+ def test_demo_user(self):
+ response = self.get_response("me")
+ assert response.status_code == 403
|
acac3431e0201a4b2bcb23261b9065b7672d697e
|
2024-01-09 00:56:21
|
Dan Fuller
|
chore(issue-platform): Add stats verify that `group_states` and the group info are the same in `post_process_group` (#62722)
| false
|
Add stats verify that `group_states` and the group info are the same in `post_process_group` (#62722)
|
chore
|
diff --git a/src/sentry/tasks/post_process.py b/src/sentry/tasks/post_process.py
index 94d7cf57805058..8fa97a49f695d6 100644
--- a/src/sentry/tasks/post_process.py
+++ b/src/sentry/tasks/post_process.py
@@ -639,6 +639,33 @@ def get_event_raise_exception() -> Event:
}
]
+ try:
+ if group_states is not None:
+ if not is_transaction_event:
+ if len(group_states) == 0:
+ metrics.incr("sentry.tasks.post_process.error_empty_group_states")
+ elif len(group_states) > 1:
+ metrics.incr("sentry.tasks.post_process.error_too_many_group_states")
+ elif group_id != group_states[0]["id"]:
+ metrics.incr(
+ "sentry.tasks.post_process.error_group_states_dont_match_group"
+ )
+ else:
+ if len(group_states) == 1:
+ metrics.incr("sentry.tasks.post_process.transaction_has_group_state")
+ if group_id != group_states[0]["id"]:
+ metrics.incr(
+ "sentry.tasks.post_process.transaction_group_states_dont_match_group"
+ )
+ if len(group_states) > 1:
+ metrics.incr(
+ "sentry.tasks.post_process.transaction_has_too_many_group_states"
+ )
+ except Exception:
+ logger.exception(
+ "Error logging group_states stats. If this happens it's noisy but not critical, nothing is broken"
+ )
+
update_event_groups(event, group_states)
bind_organization_context(event.project.organization)
_capture_event_stats(event)
|
0aceb9644d81f184e87a024c033670d39573e66a
|
2023-05-26 03:19:25
|
Leander Rodrigues
|
ref(hybrid-cloud): Add outboxing for webhook parser (#49651)
| false
|
Add outboxing for webhook parser (#49651)
|
ref
|
diff --git a/src/sentry/integrations/slack/message_builder/issues.py b/src/sentry/integrations/slack/message_builder/issues.py
index 105fb8b3521722..c1c5dfb7c00b87 100644
--- a/src/sentry/integrations/slack/message_builder/issues.py
+++ b/src/sentry/integrations/slack/message_builder/issues.py
@@ -41,8 +41,10 @@ def build_assigned_text(identity: RpcIdentity, assignee: str) -> str | None:
assignee_text = f"#{assigned_actor.slug}"
elif actor.type == User:
assignee_identity = identity_service.get_identity(
- provider_id=identity.idp_id,
- user_id=assigned_actor.id,
+ filter={
+ "provider_id": identity.idp_id,
+ "user_id": assigned_actor.id,
+ }
)
assignee_text = (
assigned_actor.get_display_name()
diff --git a/src/sentry/integrations/slack/requests/base.py b/src/sentry/integrations/slack/requests/base.py
index 92709665dc63bd..40c95c4b145c50 100644
--- a/src/sentry/integrations/slack/requests/base.py
+++ b/src/sentry/integrations/slack/requests/base.py
@@ -130,7 +130,12 @@ def get_identity(self) -> RpcIdentity | None:
provider_type="slack", provider_ext_id=self.team_id
)
self._identity = (
- identity_service.get_identity(provider_id=provider.id, identity_ext_id=self.user_id)
+ identity_service.get_identity(
+ filter={
+ "provider_id": provider.id,
+ "identity_ext_id": self.user_id,
+ }
+ )
if provider
else None
)
diff --git a/src/sentry/integrations/slack/views/link_team.py b/src/sentry/integrations/slack/views/link_team.py
index c5df0bc7de68b5..236006a3b79196 100644
--- a/src/sentry/integrations/slack/views/link_team.py
+++ b/src/sentry/integrations/slack/views/link_team.py
@@ -131,7 +131,7 @@ def handle(self, request: Request, signed_params: str) -> HttpResponse:
return render_error_page(request, body_text="HTTP 403: Invalid team ID")
ident = identity_service.get_identity(
- provider_id=idp.id, identity_ext_id=params["slack_id"]
+ filter={"provider_id": idp.id, "identity_ext_id": params["slack_id"]}
)
if not ident:
return render_error_page(request, body_text="HTTP 403: User identity does not exist")
diff --git a/src/sentry/integrations/slack/views/unlink_team.py b/src/sentry/integrations/slack/views/unlink_team.py
index 00d45b3c6bde5e..f960a5458b631d 100644
--- a/src/sentry/integrations/slack/views/unlink_team.py
+++ b/src/sentry/integrations/slack/views/unlink_team.py
@@ -96,7 +96,7 @@ def handle(self, request: Request, signed_params: str) -> Response:
)
if not idp or not identity_service.get_identity(
- provider_id=idp.id, identity_ext_id=params["slack_id"]
+ filter={"provider_id": idp.id, "identity_ext_id": params["slack_id"]}
):
return render_error_page(request, body_text="HTTP 403: User identity does not exist")
diff --git a/src/sentry/middleware/integrations/integration_control.py b/src/sentry/middleware/integrations/integration_control.py
index 7d7f63175efb64..8a003ceaa78544 100644
--- a/src/sentry/middleware/integrations/integration_control.py
+++ b/src/sentry/middleware/integrations/integration_control.py
@@ -16,6 +16,9 @@
class IntegrationControlMiddleware:
webhook_prefix: str = "/extensions/"
+ """Prefix for all integration requests. See `src/sentry/web/urls.py`"""
+ setup_suffix: str = "/setup/"
+ """Suffix for PipelineAdvancerView on installation. See `src/sentry/web/urls.py`"""
integration_parsers: Mapping[str, Type[BaseRequestParser]] = {
parser.provider: parser for parser in ACTIVE_PARSERS
@@ -45,8 +48,9 @@ def _should_operate(self, request) -> bool:
Determines whether this middleware will operate or just pass the request along.
"""
is_correct_silo = SiloMode.get_current_mode() == SiloMode.CONTROL
- is_external = request.path.startswith(self.webhook_prefix)
- return is_correct_silo and is_external
+ is_integration = request.path.startswith(self.webhook_prefix)
+ is_not_setup = not request.path.endswith(self.setup_suffix)
+ return is_correct_silo and is_integration and is_not_setup
def __call__(self, request):
if not self._should_operate(request):
diff --git a/src/sentry/middleware/integrations/parsers/base.py b/src/sentry/middleware/integrations/parsers/base.py
index b1317b28157ae6..8367c9273f2cf9 100644
--- a/src/sentry/middleware/integrations/parsers/base.py
+++ b/src/sentry/middleware/integrations/parsers/base.py
@@ -7,9 +7,11 @@
from django.http import HttpRequest, HttpResponse
from django.urls import ResolverMatch, resolve
+from rest_framework import status
from sentry.models.integrations import Integration
from sentry.models.integrations.organization_integration import OrganizationIntegration
+from sentry.models.outbox import ControlOutbox
from sentry.services.hybrid_cloud.organization import RpcOrganizationSummary, organization_service
from sentry.silo import SiloLimit, SiloMode
from sentry.silo.client import RegionSiloClient
@@ -31,12 +33,20 @@ class BaseRequestParser(abc.ABC):
def provider(self) -> str:
raise NotImplementedError("'provider' property is required by IntegrationControlMiddleware")
+ @property
+ def webhook_identifier(self) -> str:
+ raise NotImplementedError(
+ "'webhook_identifier' property is required for outboxing. Refer to WebhookProviderIdentifier enum."
+ )
+
def __init__(self, request: HttpRequest, response_handler: Callable):
self.request = request
self.match: ResolverMatch = resolve(self.request.path)
self.response_handler = response_handler
- def _ensure_control_silo(self):
+ # Common Helpers
+
+ def ensure_control_silo(self):
if SiloMode.get_current_mode() != SiloMode.CONTROL:
logger.error(
"silo_error",
@@ -46,14 +56,19 @@ def _ensure_control_silo(self):
"Integration Request Parsers should only be run on the control silo."
)
+ def is_json_request(self) -> bool:
+ return "application/json" in (self.request.headers or {}).get("Content-Type", "")
+
+ # Silo Response Helpers
+
def get_response_from_control_silo(self) -> HttpResponse:
"""
Used to handle the request directly on the control silo.
"""
- self._ensure_control_silo()
+ self.ensure_control_silo()
return self.response_handler(self.request)
- def _get_response_from_region_silo(self, region: Region) -> HttpResponse:
+ def get_response_from_region_silo(self, region: Region) -> HttpResponse:
region_client = RegionSiloClient(region)
return region_client.proxy_request(self.request).to_http_response()
@@ -63,15 +78,14 @@ def get_responses_from_region_silos(
"""
Used to handle the requests on a given list of regions (synchronously).
Returns a mapping of region name to response/exception.
- If multiple regions are provided, only the latest response is returned to the requestor.
"""
- self._ensure_control_silo()
+ self.ensure_control_silo()
region_to_response_map = {}
with ThreadPoolExecutor(max_workers=len(regions)) as executor:
future_to_region = {
- executor.submit(self._get_response_from_region_silo, region): region
+ executor.submit(self.get_response_from_region_silo, region): region
for region in regions
}
for future in as_completed(future_to_region):
@@ -94,6 +108,21 @@ def get_responses_from_region_silos(
return region_to_response_map
+ def get_response_from_outbox_creation(self, regions: Sequence[Region]):
+ """
+ Used to create outboxes for provided regions to handle the webhooks asynchronously.
+ Responds to the webhook provider with a 202 Accepted status.
+ """
+ for outbox in ControlOutbox.for_webhook_update(
+ webhook_identifier=self.webhook_identifier,
+ region_names=[region.name for region in regions],
+ request=self.request,
+ ):
+ outbox.save()
+ return HttpResponse(status=status.HTTP_202_ACCEPTED)
+
+ # Required Overrides
+
def get_response(self):
"""
Used to surface a response as part of the middleware.
@@ -109,6 +138,8 @@ def get_integration_from_request(self) -> Integration | None:
"""
return None
+ # Optional Overrides
+
def get_organizations_from_integration(
self, integration: Integration = None
) -> Sequence[RpcOrganizationSummary]:
diff --git a/src/sentry/middleware/integrations/parsers/slack.py b/src/sentry/middleware/integrations/parsers/slack.py
index 8ba3da8240b264..5b39d53eef9e10 100644
--- a/src/sentry/middleware/integrations/parsers/slack.py
+++ b/src/sentry/middleware/integrations/parsers/slack.py
@@ -7,13 +7,20 @@
from rest_framework.request import Request
from sentry.integrations.slack.requests.base import SlackRequestError
+from sentry.integrations.slack.views.link_identity import SlackLinkIdentityView
+from sentry.integrations.slack.views.link_team import SlackLinkTeamView
+from sentry.integrations.slack.views.unlink_identity import SlackUnlinkIdentityView
+from sentry.integrations.slack.views.unlink_team import SlackUnlinkTeamView
from sentry.integrations.slack.webhooks.action import (
NOTIFICATION_SETTINGS_ACTION_OPTIONS,
UNFURL_ACTION_OPTIONS,
SlackActionEndpoint,
)
from sentry.integrations.slack.webhooks.base import SlackDMEndpoint
+from sentry.integrations.slack.webhooks.command import SlackCommandsEndpoint
+from sentry.integrations.slack.webhooks.event import SlackEventEndpoint
from sentry.models.integrations.integration import Integration
+from sentry.models.outbox import WebhookProviderIdentifier
from sentry.silo.client import SiloClientError
from sentry.types.integrations import EXTERNAL_PROVIDERS, ExternalProviders
from sentry.types.region import Region
@@ -23,41 +30,41 @@
logger = logging.getLogger(__name__)
-WEBHOOK_ENDPOINTS = ["SlackCommandsEndpoint", "SlackActionEndpoint", "SlackEventEndpoint"]
-"""
-Endpoints which provide integration information in the request headers.
-See: `src/sentry/integrations/slack/webhooks`
-"""
-
-DJANGO_VIEW_ENDPOINTS = [
- "SlackLinkTeamView",
- "SlackUnlinkTeamView",
- "SlackLinkIdentityView",
- "SlackUnlinkIdentityView",
-]
-"""
-Views served directly from the control silo without React.
-See: `src/sentry/integrations/slack/views`
-"""
-
ACTIONS_ENDPOINT_ALL_SILOS_ACTIONS = UNFURL_ACTION_OPTIONS + NOTIFICATION_SETTINGS_ACTION_OPTIONS
class SlackRequestParser(BaseRequestParser):
provider = EXTERNAL_PROVIDERS[ExternalProviders.SLACK] # "slack"
+ webhook_identifier = WebhookProviderIdentifier.SLACK
control_classes = [
- "SlackLinkIdentityView",
- "SlackUnlinkIdentityView",
- "PipelineAdvancerView", # installation
+ SlackLinkIdentityView,
+ SlackUnlinkIdentityView,
]
region_classes = [
- "SlackLinkTeamView",
- "SlackUnlinkTeamView",
- "SlackCommandsEndpoint",
- "SlackEventEndpoint",
+ SlackLinkTeamView,
+ SlackUnlinkTeamView,
+ SlackCommandsEndpoint,
+ SlackEventEndpoint,
+ ]
+
+ webhook_endpoints = [SlackCommandsEndpoint, SlackActionEndpoint, SlackEventEndpoint]
+ """
+ Endpoints which provide integration info in the request headers.
+ See: `src/sentry/integrations/slack/webhooks`
+ """
+
+ django_views = [
+ SlackLinkTeamView,
+ SlackUnlinkTeamView,
+ SlackLinkIdentityView,
+ SlackUnlinkIdentityView,
]
+ """
+ Views which contain integration info in query params
+ See: `src/sentry/integrations/slack/views`
+ """
def handle_action_endpoint(self, regions: List[Region]) -> HttpResponse:
drf_request: Request = SlackDMEndpoint().initialize_request(self.request)
@@ -81,8 +88,8 @@ def handle_action_endpoint(self, regions: List[Region]) -> HttpResponse:
return successful_responses[0].response
def get_integration_from_request(self) -> Integration | None:
- view_class_name = self.match.func.view_class.__name__
- if view_class_name in WEBHOOK_ENDPOINTS:
+ view_class = self.match.func.view_class
+ if view_class in self.webhook_endpoints:
# We need convert the raw Django request to a Django Rest Framework request
# since that's the type the SlackRequest expects
drf_request: Request = SlackDMEndpoint().initialize_request(self.request)
@@ -95,7 +102,7 @@ def get_integration_from_request(self) -> Integration | None:
return None
return Integration.objects.filter(id=slack_request.integration.id).first()
- elif view_class_name in DJANGO_VIEW_ENDPOINTS:
+ elif view_class in self.django_views:
# Parse the signed params to identify the associated integration
params = unsign(self.match.kwargs.get("signed_params"))
return Integration.objects.filter(id=params.get("integration_id")).first()
@@ -134,18 +141,16 @@ def get_response(self):
"""
Slack Webhook Requests all require synchronous responses.
"""
- view_class_name = self.match.func.view_class.__name__
+ view_class = self.match.func.view_class
+ if view_class in self.control_classes:
+ return self.get_response_from_control_silo()
regions = self.get_regions_from_organizations()
if len(regions) == 0:
logger.error("no_regions", extra={"path": self.request.path})
return self.get_response_from_control_silo()
- view_class_name = self.match.func.view_class.__name__
- if view_class_name in self.control_classes:
- return self.get_response_from_control_silo()
-
- if view_class_name == "SlackActionEndpoint":
+ if view_class == SlackActionEndpoint:
drf_request: Request = SlackDMEndpoint().initialize_request(self.request)
slack_request = self.match.func.view_class.slack_request_class(drf_request)
action_option = SlackActionEndpoint.get_action_option(slack_request=slack_request)
diff --git a/src/sentry/models/outbox.py b/src/sentry/models/outbox.py
index ae5e9741a28be3..b15dc0a1b79969 100644
--- a/src/sentry/models/outbox.py
+++ b/src/sentry/models/outbox.py
@@ -2,6 +2,7 @@
import abc
import contextlib
+import dataclasses
import datetime
from enum import IntEnum
from typing import Any, Generator, Iterable, List, Mapping, Type, TypeVar
@@ -9,6 +10,7 @@
from django.db import connections, models, router, transaction
from django.db.models import Max
from django.dispatch import Signal
+from django.http import HttpRequest
from django.utils import timezone
from sentry.db.models import (
@@ -68,6 +70,15 @@ def as_choices(cls):
return [(i.value, i.value) for i in cls]
[email protected]
+class OutboxWebhookPayload:
+ method: str
+ path: str
+ uri: str
+ headers: Mapping[str, Any]
+ body: str
+
+
class WebhookProviderIdentifier(IntEnum):
SLACK = 0
GITHUB = 1
@@ -314,13 +325,32 @@ class Meta:
"region_name", "shard_scope", "shard_identifier", "category", "object_identifier"
)
+ def get_webhook_payload_from_request(self, request: HttpRequest) -> OutboxWebhookPayload:
+ return OutboxWebhookPayload(
+ method=request.method,
+ path=request.path,
+ uri=request.get_raw_uri(),
+ headers={k: v for k, v in request.headers.items()},
+ body=request.body.decode(encoding="utf-8"),
+ )
+
+ @classmethod
+ def get_webhook_payload_from_outbox(self, payload: Mapping[str, Any]) -> OutboxWebhookPayload:
+ return OutboxWebhookPayload(
+ method=payload.get("method"),
+ path=payload.get("path"),
+ uri=payload.get("uri"),
+ headers=payload.get("headers"),
+ body=payload.get("body"),
+ )
+
@classmethod
def for_webhook_update(
cls,
*,
webhook_identifier: WebhookProviderIdentifier,
region_names: List[str],
- payload=Mapping[str, Any],
+ request: HttpRequest,
) -> Iterable[ControlOutbox]:
for region_name in region_names:
result = cls()
@@ -329,7 +359,8 @@ def for_webhook_update(
result.object_identifier = cls.next_object_identifier()
result.category = OutboxCategory.WEBHOOK_PROXY
result.region_name = region_name
- result.payload = payload
+ payload: OutboxWebhookPayload = result.get_webhook_payload_from_request(request)
+ result.payload = dataclasses.asdict(payload)
yield result
@classmethod
diff --git a/src/sentry/receivers/outbox/control.py b/src/sentry/receivers/outbox/control.py
index 2a7d63e620b008..2f43a6039210a9 100644
--- a/src/sentry/receivers/outbox/control.py
+++ b/src/sentry/receivers/outbox/control.py
@@ -7,7 +7,8 @@
"""
from __future__ import annotations
-from typing import Any
+import logging
+from typing import Any, Mapping
from django.dispatch import receiver
@@ -21,6 +22,9 @@
process_control_outbox,
)
from sentry.receivers.outbox import maybe_process_tombstone
+from sentry.silo.base import SiloMode
+
+logger = logging.getLogger(__name__)
@receiver(process_control_outbox, sender=OutboxCategory.USER_UPDATE)
@@ -62,3 +66,32 @@ def process_organization_integration_update(object_identifier: int, **kwds: Any)
) is None:
return
organization_integration # Currently we do not sync any other organization integration changes, but if we did, you can use this variable.
+
+
+@receiver(process_control_outbox, sender=OutboxCategory.WEBHOOK_PROXY)
+def process_async_webhooks(payload: Mapping[str, Any], region_name: str, **kwds: Any):
+ from sentry.models.outbox import ControlOutbox
+ from sentry.silo.client import RegionSiloClient
+ from sentry.types.region import get_region_by_name
+
+ region = get_region_by_name(name=region_name)
+ webhook_payload = ControlOutbox.get_webhook_payload_from_outbox(payload=payload)
+
+ if SiloMode.get_current_mode() == SiloMode.CONTROL:
+ # By default, these clients will raise errors on non-20x response codes
+ response = RegionSiloClient(region=region).request(
+ method=webhook_payload.method,
+ path=webhook_payload.path,
+ headers=webhook_payload.headers,
+ # We need to send the body as raw bytes to avoid interfering with webhook signatures
+ data=webhook_payload.body,
+ json=False,
+ )
+ logger.info(
+ "webhook_proxy.complete",
+ extra={
+ "status": response.status_code,
+ "request_path": webhook_payload.path,
+ "request_method": webhook_payload.method,
+ },
+ )
diff --git a/src/sentry/services/hybrid_cloud/identity/impl.py b/src/sentry/services/hybrid_cloud/identity/impl.py
index 5b98e9c8fce464..dfa7f8996d8940 100644
--- a/src/sentry/services/hybrid_cloud/identity/impl.py
+++ b/src/sentry/services/hybrid_cloud/identity/impl.py
@@ -1,13 +1,23 @@
from __future__ import annotations
-from typing import Any, List
+from typing import Any, Callable, List, Optional
+from django.db.models import QuerySet
+
+from sentry.api.serializers.base import Serializer
from sentry.models import AuthIdentity
-from sentry.services.hybrid_cloud.identity import IdentityService, RpcIdentity, RpcIdentityProvider
+from sentry.models.identity import Identity
+from sentry.services.hybrid_cloud.filter_query import FilterQueryDatabaseImpl
+from sentry.services.hybrid_cloud.identity.model import (
+ IdentityFilterArgs,
+ RpcIdentity,
+ RpcIdentityProvider,
+)
from sentry.services.hybrid_cloud.identity.serial import (
serialize_identity,
serialize_identity_provider,
)
+from sentry.services.hybrid_cloud.identity.service import IdentityService
class DatabaseBackedIdentityService(IdentityService):
@@ -34,21 +44,14 @@ def get_provider(
return serialize_identity_provider(idp) if idp else None
- def get_identity(
- self,
- *,
- provider_id: int,
- user_id: int | None = None,
- identity_ext_id: str | None = None,
- ) -> RpcIdentity | None:
- from sentry.models.identity import Identity
-
- # If an user_id is provided, use that -- otherwise, use the external_id
- identity_kwargs: Any = {"user_id": user_id} if user_id else {"external_id": identity_ext_id}
+ def get_identities(self, *, filter: IdentityFilterArgs) -> List[RpcIdentity]:
+ return self._FQ.get_many(filter=filter)
- identity = Identity.objects.filter(**identity_kwargs, idp_id=provider_id).first()
-
- return serialize_identity(identity) if identity else None
+ def get_identity(self, *, filter: IdentityFilterArgs) -> RpcIdentity | None:
+ identities = self.get_identities(filter=filter)
+ if len(identities) == 0:
+ return None
+ return identities[0]
def get_user_identities_by_provider_type(
self,
@@ -81,3 +84,39 @@ def delete_identities(self, user_id: int, organization_id: int) -> None:
AuthIdentity.objects.filter(
user_id=user_id, auth_provider__organization_id=organization_id
).delete()
+
+ class _IdentityFilterQuery(
+ FilterQueryDatabaseImpl[Identity, IdentityFilterArgs, RpcIdentity, None]
+ ):
+ def apply_filters(self, query: QuerySet, filters: IdentityFilterArgs) -> QuerySet:
+ if "user_id" in filters:
+ query = query.filter(user_id=filters["user_id"])
+ if "identity_ext_id" in filters:
+ query = query.filter(external_id=filters["identity_ext_id"])
+ if "provider_id" in filters:
+ query = query.filter(idp_id=filters["provider_id"])
+ if "provider_ext_id" in filters:
+ query = query.filter(idp__external_id=filters["provider_ext_id"])
+ if "provider_type" in filters:
+ query = query.filter(idp__type=filters["provider_type"])
+ return query
+
+ def base_query(self) -> QuerySet:
+ return Identity.objects
+
+ def filter_arg_validator(self) -> Callable[[IdentityFilterArgs], Optional[str]]:
+ return self._filter_has_any_key_validator(
+ "user_id",
+ "identity_ext_id",
+ "provider_id",
+ "provider_ext_id",
+ "provider_type",
+ )
+
+ def serialize_api(self, serializer: Optional[None]) -> Serializer:
+ raise NotImplementedError("API Serialization not supported for IdentityService")
+
+ def serialize_rpc(self, identity: Identity) -> RpcIdentity:
+ return serialize_identity(identity=identity)
+
+ _FQ = _IdentityFilterQuery()
diff --git a/src/sentry/services/hybrid_cloud/identity/model.py b/src/sentry/services/hybrid_cloud/identity/model.py
index 3f52660dc8fac2..05c2b6c0f33056 100644
--- a/src/sentry/services/hybrid_cloud/identity/model.py
+++ b/src/sentry/services/hybrid_cloud/identity/model.py
@@ -2,6 +2,7 @@
# from __future__ import annotations
# in modules such as this one where hybrid cloud data models or service classes are
# defined, because we want to reflect on type annotations and avoid forward references.
+from typing_extensions import TypedDict
from sentry.services.hybrid_cloud import RpcModel
@@ -17,3 +18,11 @@ class RpcIdentity(RpcModel):
idp_id: int
user_id: int
external_id: str
+
+
+class IdentityFilterArgs(TypedDict, total=False):
+ user_id: int
+ identity_ext_id: str
+ provider_id: int
+ provider_ext_id: str
+ provider_type: str
diff --git a/src/sentry/shared_integrations/client/proxy.py b/src/sentry/shared_integrations/client/proxy.py
index b2fd26065aebf6..bbfccc86d2c11b 100644
--- a/src/sentry/shared_integrations/client/proxy.py
+++ b/src/sentry/shared_integrations/client/proxy.py
@@ -65,7 +65,7 @@ def authorize_request(self, prepared_request: PreparedRequest) -> PreparedReques
def finalize_request(self, prepared_request: PreparedRequest) -> PreparedRequest:
"""
- Every request through this subclassed clients run this method.
+ Every request through these subclassed clients run this method.
If running as a monolith/control, we must authorize each request before sending.
If running as a region, we don't authorize and instead, send it to our proxy endpoint,
where tokens are added in by Control Silo. We do this to avoid race conditions around
diff --git a/src/sentry/silo/client.py b/src/sentry/silo/client.py
index c60de3d9f527eb..b3daa2f0535aac 100644
--- a/src/sentry/silo/client.py
+++ b/src/sentry/silo/client.py
@@ -64,8 +64,10 @@ def request(
method: str,
path: str,
headers: Mapping[str, Any] | None = None,
- data: Mapping[str, Any] | None = None,
+ data: Any | None = None,
params: Mapping[str, Any] | None = None,
+ json: bool = True,
+ raw_response: bool = False,
) -> BaseApiResponseX:
"""
Use the BaseApiClient interface to send a cross-region request.
@@ -79,8 +81,9 @@ def request(
headers=clean_proxy_headers(headers),
data=data,
params=params,
- json=True,
+ json=json,
allow_text=True,
+ raw_response=raw_response,
)
# TODO: Establish a scheme to check/log the Sentry Version of the requestor and server
# optionally raising an error to alert developers of version drift
diff --git a/tests/sentry/middleware/integrations/parsers/test_base.py b/tests/sentry/middleware/integrations/parsers/test_base.py
index 5af7f1717aa1cf..23002b2196623a 100644
--- a/tests/sentry/middleware/integrations/parsers/test_base.py
+++ b/tests/sentry/middleware/integrations/parsers/test_base.py
@@ -1,10 +1,19 @@
+import dataclasses
from typing import Iterable
from unittest.mock import MagicMock, patch
+import pytest
from django.test import RequestFactory, override_settings
from pytest import raises
+from rest_framework import status
from sentry.middleware.integrations.parsers.base import BaseRequestParser
+from sentry.models.outbox import (
+ ControlOutbox,
+ OutboxCategory,
+ OutboxScope,
+ WebhookProviderIdentifier,
+)
from sentry.silo.base import SiloLimit, SiloMode
from sentry.testutils import TestCase
from sentry.types.region import Region, RegionCategory
@@ -50,7 +59,7 @@ def test_get_response_from_control_silo(self):
assert response == self.response_handler(self.request)
@override_settings(SILO_MODE=SiloMode.CONTROL)
- @patch.object(BaseRequestParser, "_get_response_from_region_silo")
+ @patch.object(BaseRequestParser, "get_response_from_region_silo")
def test_get_responses_from_region_silos(self, mock__get_response):
mock__get_response.side_effect = lambda region: region.name
@@ -61,7 +70,7 @@ def test_get_responses_from_region_silos(self, mock__get_response):
assert response_map[region.name].response == region.name
@override_settings(SILO_MODE=SiloMode.CONTROL)
- @patch.object(BaseRequestParser, "_get_response_from_region_silo")
+ @patch.object(BaseRequestParser, "get_response_from_region_silo")
def test_get_responses_from_region_silos_with_partial_failure(self, mock__get_response):
mock__get_response.side_effect = lambda region: error_regions(region, ["eu"])
@@ -71,7 +80,7 @@ def test_get_responses_from_region_silos_with_partial_failure(self, mock__get_re
assert type(response_map["eu"].error) is SiloLimit.AvailabilityError
@override_settings(SILO_MODE=SiloMode.CONTROL)
- @patch.object(BaseRequestParser, "_get_response_from_region_silo")
+ @patch.object(BaseRequestParser, "get_response_from_region_silo")
def test_get_responses_from_region_silos_with_complete_failure(self, mock__get_response):
mock__get_response.side_effect = lambda region: error_regions(region, ["na", "eu"])
@@ -81,3 +90,25 @@ def test_get_responses_from_region_silos_with_complete_failure(self, mock__get_r
for region in self.region_config:
assert type(response_map[region.name].error) is SiloLimit.AvailabilityError
+
+ @override_settings(SILO_MODE=SiloMode.CONTROL)
+ def test_get_response_from_outbox_creation(self):
+ with pytest.raises(NotImplementedError):
+ self.parser.get_response_from_outbox_creation(regions=self.region_config)
+
+ class MockParser(BaseRequestParser):
+ webhook_identifier = WebhookProviderIdentifier.SLACK
+
+ parser = MockParser(self.request, self.response_handler)
+
+ response = parser.get_response_from_outbox_creation(regions=self.region_config)
+ assert response.status_code == status.HTTP_202_ACCEPTED
+ new_outboxes = ControlOutbox.objects.all()
+ assert len(new_outboxes) == 2
+ for outbox in new_outboxes:
+ assert outbox.region_name in ["na", "eu"]
+ assert outbox.category == OutboxCategory.WEBHOOK_PROXY
+ assert outbox.shard_scope == OutboxScope.WEBHOOK_SCOPE
+ assert outbox.shard_identifier == WebhookProviderIdentifier.SLACK.value
+ payload = outbox.get_webhook_payload_from_request(self.request)
+ assert outbox.payload == dataclasses.asdict(payload)
diff --git a/tests/sentry/models/test_outbox.py b/tests/sentry/models/test_outbox.py
index c63439ebe124ce..10d98e91e910f2 100644
--- a/tests/sentry/models/test_outbox.py
+++ b/tests/sentry/models/test_outbox.py
@@ -1,10 +1,13 @@
+import dataclasses
from datetime import datetime, timedelta
from typing import ContextManager
from unittest.mock import call, patch
-import pytest
+import responses
+from django.test import RequestFactory, override_settings
from freezegun import freeze_time
from pytest import raises
+from rest_framework import status
from sentry.models import (
ControlOutbox,
@@ -17,252 +20,343 @@
WebhookProviderIdentifier,
)
from sentry.services.hybrid_cloud.organization import organization_service
+from sentry.shared_integrations.exceptions.base import ApiError
from sentry.silo import SiloMode
from sentry.tasks.deliver_from_outbox import enqueue_outbox_jobs
+from sentry.testutils import TestCase
from sentry.testutils.factories import Factories
from sentry.testutils.outbox import outbox_runner
from sentry.testutils.silo import control_silo_test, exempt_from_silo_limits, region_silo_test
-from sentry.types.region import MONOLITH_REGION_NAME
+from sentry.types.region import MONOLITH_REGION_NAME, Region, RegionCategory
[email protected]_db(transaction=True)
-@region_silo_test(stable=True)
-def test_creating_org_outboxes():
- Organization.outbox_for_update(10).save()
- OrganizationMember(organization_id=12, id=15).outbox_for_update().save()
- assert RegionOutbox.objects.count() == 2
+@control_silo_test(stable=True)
+class ControlOutboxTest(TestCase):
+ webhook_request = RequestFactory().post(
+ "/extensions/github/webhook/",
+ data={"installation": {"id": "github:1"}},
+ content_type="application/json",
+ HTTP_X_GITHUB_EMOTICON=">:^]",
+ )
+ region = Region("eu", 1, "http://eu.testserver", RegionCategory.MULTI_TENANT)
+ region_config = (region,)
+
+ def test_creating_user_outboxes(self):
+ with exempt_from_silo_limits():
+ org = Factories.create_organization(no_mapping=True)
+ Factories.create_org_mapping(org, region_name="a")
+ user1 = Factories.create_user()
+ organization_service.add_organization_member(
+ organization_id=org.id,
+ default_org_role=org.default_role,
+ user_id=user1.id,
+ )
- with exempt_from_silo_limits(), outbox_runner():
- # drain outboxes
- pass
- assert RegionOutbox.objects.count() == 0
+ org2 = Factories.create_organization(no_mapping=True)
+ Factories.create_org_mapping(org2, region_name="b")
+ organization_service.add_organization_member(
+ organization_id=org2.id,
+ default_org_role=org2.default_role,
+ user_id=user1.id,
+ )
+ for outbox in User.outboxes_for_update(user1.id):
+ outbox.save()
+
+ expected_counts = 1 if SiloMode.get_current_mode() == SiloMode.MONOLITH else 2
+ assert ControlOutbox.objects.count() == expected_counts
+
+ def test_control_sharding_keys(self):
+ request = RequestFactory().get("/extensions/slack/webhook/")
+ with exempt_from_silo_limits():
+ org = Factories.create_organization(no_mapping=True)
+ Factories.create_org_mapping(org, region_name=MONOLITH_REGION_NAME)
+ user1 = Factories.create_user()
+ user2 = Factories.create_user()
+ organization_service.add_organization_member(
+ organization_id=org.id,
+ default_org_role=org.default_role,
+ user_id=user1.id,
+ )
+ organization_service.add_organization_member(
+ organization_id=org.id,
+ default_org_role=org.default_role,
+ user_id=user2.id,
+ )
[email protected]_db(transaction=True)
-@control_silo_test(stable=True)
-def test_creating_user_outboxes():
- with exempt_from_silo_limits():
- org = Factories.create_organization(no_mapping=True)
- Factories.create_org_mapping(org, region_name="a")
- user1 = Factories.create_user()
- organization_service.add_organization_member(
- organization_id=org.id,
- default_org_role=org.default_role,
- user_id=user1.id,
+ for inst in User.outboxes_for_update(user1.id):
+ inst.save()
+ for inst in User.outboxes_for_update(user2.id):
+ inst.save()
+
+ for inst in ControlOutbox.for_webhook_update(
+ webhook_identifier=WebhookProviderIdentifier.SLACK,
+ region_names=[MONOLITH_REGION_NAME, "special-slack-region"],
+ request=request,
+ ):
+ inst.save()
+
+ for inst in ControlOutbox.for_webhook_update(
+ webhook_identifier=WebhookProviderIdentifier.GITHUB,
+ region_names=[MONOLITH_REGION_NAME, "special-github-region"],
+ request=request,
+ ):
+ inst.save()
+
+ shards = {
+ (row["shard_scope"], row["shard_identifier"], row["region_name"])
+ for row in ControlOutbox.find_scheduled_shards()
+ }
+ assert shards == {
+ (OutboxScope.USER_SCOPE.value, user1.id, MONOLITH_REGION_NAME),
+ (OutboxScope.USER_SCOPE.value, user2.id, MONOLITH_REGION_NAME),
+ (
+ OutboxScope.WEBHOOK_SCOPE.value,
+ WebhookProviderIdentifier.SLACK,
+ MONOLITH_REGION_NAME,
+ ),
+ (
+ OutboxScope.WEBHOOK_SCOPE.value,
+ WebhookProviderIdentifier.GITHUB,
+ MONOLITH_REGION_NAME,
+ ),
+ (
+ OutboxScope.WEBHOOK_SCOPE.value,
+ WebhookProviderIdentifier.SLACK,
+ "special-slack-region",
+ ),
+ (
+ OutboxScope.WEBHOOK_SCOPE.value,
+ WebhookProviderIdentifier.GITHUB,
+ "special-github-region",
+ ),
+ }
+
+ def test_control_outbox_for_webhooks(self):
+ [outbox] = ControlOutbox.for_webhook_update(
+ webhook_identifier=WebhookProviderIdentifier.GITHUB,
+ region_names=["webhook-region"],
+ request=self.webhook_request,
)
-
- org2 = Factories.create_organization(no_mapping=True)
- Factories.create_org_mapping(org2, region_name="b")
- organization_service.add_organization_member(
- organization_id=org2.id,
- default_org_role=org2.default_role,
- user_id=user1.id,
+ assert outbox.shard_scope == OutboxScope.WEBHOOK_SCOPE
+ assert outbox.shard_identifier == WebhookProviderIdentifier.GITHUB
+ assert outbox.category == OutboxCategory.WEBHOOK_PROXY
+ assert outbox.region_name == "webhook-region"
+
+ payload_from_request = outbox.get_webhook_payload_from_request(self.webhook_request)
+ assert outbox.payload == dataclasses.asdict(payload_from_request)
+ payload_from_outbox = outbox.get_webhook_payload_from_outbox(outbox.payload)
+ assert payload_from_request == payload_from_outbox
+
+ assert outbox.payload["method"] == "POST"
+ assert outbox.payload["path"] == "/extensions/github/webhook/"
+ assert outbox.payload["uri"] == "http://testserver/extensions/github/webhook/"
+ # Request factory expects transformed headers, but the outbox stores raw headers
+ assert outbox.payload["headers"]["X-Github-Emoticon"] == ">:^]"
+ assert outbox.payload["body"] == '{"installation": {"id": "github:1"}}'
+
+ # After saving, data shouldn't mutate
+ outbox.save()
+ outbox = ControlOutbox.objects.all().first()
+ assert outbox.payload["method"] == "POST"
+ assert outbox.payload["path"] == "/extensions/github/webhook/"
+ assert outbox.payload["uri"] == "http://testserver/extensions/github/webhook/"
+ # Request factory expects transformed headers, but the outbox stores raw headers
+ assert outbox.payload["headers"]["X-Github-Emoticon"] == ">:^]"
+ assert outbox.payload["body"] == '{"installation": {"id": "github:1"}}'
+
+ @responses.activate
+ @override_settings(SENTRY_REGION_CONFIG=region_config)
+ def test_drains_successful_success(self):
+ mock_response = responses.add(
+ self.webhook_request.method,
+ f"{self.region.address}{self.webhook_request.path}",
+ status=status.HTTP_200_OK,
+ )
+ expected_request_count = 1 if SiloMode.get_current_mode() == SiloMode.CONTROL else 0
+ [outbox] = ControlOutbox.for_webhook_update(
+ webhook_identifier=WebhookProviderIdentifier.GITHUB,
+ region_names=[self.region.name],
+ request=self.webhook_request,
)
-
- for outbox in User.outboxes_for_update(user1.id):
outbox.save()
- expected_counts = 1 if SiloMode.get_current_mode() == SiloMode.MONOLITH else 2
- assert ControlOutbox.objects.count() == expected_counts
+ assert ControlOutbox.objects.filter(id=outbox.id).exists()
+ outbox.drain_shard()
+ assert mock_response.call_count == expected_request_count
+ assert not ControlOutbox.objects.filter(id=outbox.id).exists()
+
+ @responses.activate
+ @override_settings(SENTRY_REGION_CONFIG=region_config)
+ def test_drains_webhook_failure(self):
+ mock_response = responses.add(
+ self.webhook_request.method,
+ f"{self.region.address}{self.webhook_request.path}",
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+ [outbox] = ControlOutbox.for_webhook_update(
+ webhook_identifier=WebhookProviderIdentifier.GITHUB,
+ region_names=[self.region.name],
+ request=self.webhook_request,
+ )
+ outbox.save()
+ assert ControlOutbox.objects.filter(id=outbox.id).exists()
+ if SiloMode.get_current_mode() == SiloMode.CONTROL:
+ with raises(ApiError):
+ outbox.drain_shard()
+ assert mock_response.call_count == 1
+ assert ControlOutbox.objects.filter(id=outbox.id).exists()
+ else:
+ outbox.drain_shard()
+ assert mock_response.call_count == 0
+ assert not ControlOutbox.objects.filter(id=outbox.id).exists()
[email protected]_db(transaction=True)
-@region_silo_test(stable=True)
-@patch("sentry.models.outbox.metrics")
-def test_concurrent_coalesced_object_processing(mock_metrics):
- # Two objects coalesced
- outbox = OrganizationMember(id=1, organization_id=1).outbox_for_update()
- outbox.save()
- OrganizationMember(id=1, organization_id=1).outbox_for_update().save()
-
- # Unrelated
- OrganizationMember(organization_id=1, id=2).outbox_for_update().save()
- OrganizationMember(organization_id=2, id=2).outbox_for_update().save()
-
- assert len(list(RegionOutbox.find_scheduled_shards())) == 2
-
- ctx: ContextManager = outbox.process_coalesced()
- try:
- ctx.__enter__()
- assert RegionOutbox.objects.count() == 4
- assert outbox.select_coalesced_messages().count() == 2
-
- # concurrent write of coalesced object update.
- OrganizationMember(organization_id=1, id=1).outbox_for_update().save()
- assert RegionOutbox.objects.count() == 5
- assert outbox.select_coalesced_messages().count() == 3
-
- ctx.__exit__(None, None, None)
-
- # does not remove the concurrent write, which is still going to update.
- assert RegionOutbox.objects.count() == 3
- assert outbox.select_coalesced_messages().count() == 1
- assert len(list(RegionOutbox.find_scheduled_shards())) == 2
- expected = [
- call("outbox.saved", 1, tags={"category": "ORGANIZATION_MEMBER_UPDATE"}),
- call("outbox.saved", 1, tags={"category": "ORGANIZATION_MEMBER_UPDATE"}),
- call("outbox.saved", 1, tags={"category": "ORGANIZATION_MEMBER_UPDATE"}),
- call("outbox.saved", 1, tags={"category": "ORGANIZATION_MEMBER_UPDATE"}),
- call("outbox.saved", 1, tags={"category": "ORGANIZATION_MEMBER_UPDATE"}),
- call("outbox.processed", 2, tags={"category": "ORGANIZATION_MEMBER_UPDATE"}),
- ]
- assert mock_metrics.incr.mock_calls == expected
- except Exception as e:
- ctx.__exit__(type(e), e, None)
- raise e
-
-
[email protected]_db(transaction=True)
@region_silo_test(stable=True)
-def test_region_sharding_keys():
- org1 = Factories.create_organization(no_mapping=True)
- org2 = Factories.create_organization(no_mapping=True)
-
- Organization.outbox_for_update(org1.id).save()
- Organization.outbox_for_update(org2.id).save()
-
- OrganizationMember(organization_id=org1.id, id=1).outbox_for_update().save()
- OrganizationMember(organization_id=org2.id, id=2).outbox_for_update().save()
-
- shards = {
- (row["shard_scope"], row["shard_identifier"])
- for row in RegionOutbox.find_scheduled_shards()
- }
- assert shards == {
- (OutboxScope.ORGANIZATION_SCOPE.value, org1.id),
- (OutboxScope.ORGANIZATION_SCOPE.value, org2.id),
- }
-
-
[email protected]_db(transaction=True)
-@control_silo_test(stable=True)
-def test_control_sharding_keys():
- with exempt_from_silo_limits():
- org = Factories.create_organization(no_mapping=True)
- Factories.create_org_mapping(org, region_name=MONOLITH_REGION_NAME)
- user1 = Factories.create_user()
- user2 = Factories.create_user()
- organization_service.add_organization_member(
- organization_id=org.id,
- default_org_role=org.default_role,
- user_id=user1.id,
- )
- organization_service.add_organization_member(
- organization_id=org.id,
- default_org_role=org.default_role,
- user_id=user2.id,
- )
+class RegionOutboxTest(TestCase):
+ def test_creating_org_outboxes(self):
+ Organization.outbox_for_update(10).save()
+ OrganizationMember(organization_id=12, id=15).outbox_for_update().save()
+ assert RegionOutbox.objects.count() == 2
+
+ with exempt_from_silo_limits(), outbox_runner():
+ # drain outboxes
+ pass
+ assert RegionOutbox.objects.count() == 0
+
+ @patch("sentry.models.outbox.metrics")
+ def test_concurrent_coalesced_object_processing(self, mock_metrics):
+ # Two objects coalesced
+ outbox = OrganizationMember(id=1, organization_id=1).outbox_for_update()
+ outbox.save()
+ OrganizationMember(id=1, organization_id=1).outbox_for_update().save()
- for inst in User.outboxes_for_update(user1.id):
- inst.save()
- for inst in User.outboxes_for_update(user2.id):
- inst.save()
-
- for inst in ControlOutbox.for_webhook_update(
- webhook_identifier=WebhookProviderIdentifier.SLACK,
- region_names=[MONOLITH_REGION_NAME, "special-slack-region"],
- ):
- inst.save()
-
- for inst in ControlOutbox.for_webhook_update(
- webhook_identifier=WebhookProviderIdentifier.GITHUB,
- region_names=[MONOLITH_REGION_NAME, "special-github-region"],
- ):
- inst.save()
-
- shards = {
- (row["shard_scope"], row["shard_identifier"], row["region_name"])
- for row in ControlOutbox.find_scheduled_shards()
- }
- assert shards == {
- (OutboxScope.USER_SCOPE.value, user1.id, MONOLITH_REGION_NAME),
- (OutboxScope.USER_SCOPE.value, user2.id, MONOLITH_REGION_NAME),
- (OutboxScope.WEBHOOK_SCOPE.value, WebhookProviderIdentifier.SLACK, MONOLITH_REGION_NAME),
- (OutboxScope.WEBHOOK_SCOPE.value, WebhookProviderIdentifier.GITHUB, MONOLITH_REGION_NAME),
- (OutboxScope.WEBHOOK_SCOPE.value, WebhookProviderIdentifier.SLACK, "special-slack-region"),
- (
- OutboxScope.WEBHOOK_SCOPE.value,
- WebhookProviderIdentifier.GITHUB,
- "special-github-region",
- ),
- }
-
-
[email protected]_db(transaction=True)
-@region_silo_test(stable=True)
-def test_outbox_rescheduling(task_runner):
- with patch("sentry.models.outbox.process_region_outbox.send") as mock_process_region_outbox:
+ # Unrelated
+ OrganizationMember(organization_id=1, id=2).outbox_for_update().save()
+ OrganizationMember(organization_id=2, id=2).outbox_for_update().save()
- def raise_exception(**kwds):
- raise ValueError("This is just a test mock exception")
+ assert len(list(RegionOutbox.find_scheduled_shards())) == 2
- def run_with_error():
- mock_process_region_outbox.side_effect = raise_exception
- mock_process_region_outbox.reset_mock()
- with task_runner():
- with raises(ValueError):
+ ctx: ContextManager = outbox.process_coalesced()
+ try:
+ ctx.__enter__()
+ assert RegionOutbox.objects.count() == 4
+ assert outbox.select_coalesced_messages().count() == 2
+
+ # concurrent write of coalesced object update.
+ OrganizationMember(organization_id=1, id=1).outbox_for_update().save()
+ assert RegionOutbox.objects.count() == 5
+ assert outbox.select_coalesced_messages().count() == 3
+
+ ctx.__exit__(None, None, None)
+
+ # does not remove the concurrent write, which is still going to update.
+ assert RegionOutbox.objects.count() == 3
+ assert outbox.select_coalesced_messages().count() == 1
+ assert len(list(RegionOutbox.find_scheduled_shards())) == 2
+
+ expected = [
+ call("outbox.saved", 1, tags={"category": "ORGANIZATION_MEMBER_UPDATE"}),
+ call("outbox.saved", 1, tags={"category": "ORGANIZATION_MEMBER_UPDATE"}),
+ call("outbox.saved", 1, tags={"category": "ORGANIZATION_MEMBER_UPDATE"}),
+ call("outbox.saved", 1, tags={"category": "ORGANIZATION_MEMBER_UPDATE"}),
+ call("outbox.saved", 1, tags={"category": "ORGANIZATION_MEMBER_UPDATE"}),
+ call("outbox.processed", 2, tags={"category": "ORGANIZATION_MEMBER_UPDATE"}),
+ ]
+ assert mock_metrics.incr.mock_calls == expected
+ except Exception as e:
+ ctx.__exit__(type(e), e, None)
+ raise e
+
+ def test_outbox_rescheduling(self):
+ with patch("sentry.models.outbox.process_region_outbox.send") as mock_process_region_outbox:
+
+ def raise_exception(**kwds):
+ raise ValueError("This is just a test mock exception")
+
+ def run_with_error():
+ mock_process_region_outbox.side_effect = raise_exception
+ mock_process_region_outbox.reset_mock()
+ with self.tasks():
+ with raises(ValueError):
+ enqueue_outbox_jobs()
+ assert mock_process_region_outbox.call_count == 1
+
+ def ensure_converged():
+ mock_process_region_outbox.reset_mock()
+ with self.tasks():
enqueue_outbox_jobs()
- assert mock_process_region_outbox.call_count == 1
-
- def ensure_converged():
- mock_process_region_outbox.reset_mock()
- with task_runner():
- enqueue_outbox_jobs()
- assert mock_process_region_outbox.call_count == 0
-
- def assert_called_for_org(org):
- mock_process_region_outbox.assert_called_with(
- sender=OutboxCategory.ORGANIZATION_UPDATE,
- payload=None,
- object_identifier=org,
- shard_identifier=org,
- )
-
- Organization.outbox_for_update(org_id=10001).save()
- Organization.outbox_for_update(org_id=10002).save()
+ assert mock_process_region_outbox.call_count == 0
+
+ def assert_called_for_org(org):
+ mock_process_region_outbox.assert_called_with(
+ sender=OutboxCategory.ORGANIZATION_UPDATE,
+ payload=None,
+ object_identifier=org,
+ shard_identifier=org,
+ )
+
+ Organization.outbox_for_update(org_id=10001).save()
+ Organization.outbox_for_update(org_id=10002).save()
+
+ start_time = datetime(2022, 10, 1, 0)
+ with freeze_time(start_time):
+ run_with_error()
+ assert_called_for_org(10001)
+
+ # Runs things in ascending order of the scheduled_for
+ with freeze_time(start_time + timedelta(minutes=10)):
+ run_with_error()
+ assert_called_for_org(10002)
+
+ # Has rescheduled all objects into the future.
+ with freeze_time(start_time):
+ ensure_converged()
+
+ # Next would run the original rescheduled org1 entry
+ with freeze_time(start_time + timedelta(minutes=10)):
+ run_with_error()
+ assert_called_for_org(10001)
+ ensure_converged()
+
+ # Concurrently added items still follow the largest retry schedule
+ Organization.outbox_for_update(10002).save()
+ ensure_converged()
+
+ def test_outbox_converges(self):
+ with patch("sentry.models.outbox.process_region_outbox.send") as mock_process_region_outbox:
+ Organization.outbox_for_update(10001).save()
+ Organization.outbox_for_update(10001).save()
- start_time = datetime(2022, 10, 1, 0)
- with freeze_time(start_time):
- run_with_error()
- assert_called_for_org(10001)
+ Organization.outbox_for_update(10002).save()
+ Organization.outbox_for_update(10002).save()
- # Runs things in ascending order of the scheduled_for
- with freeze_time(start_time + timedelta(minutes=10)):
- run_with_error()
- assert_called_for_org(10002)
+ last_call_count = 0
+ while True:
+ with self.tasks():
+ enqueue_outbox_jobs()
+ if last_call_count == mock_process_region_outbox.call_count:
+ break
+ last_call_count = mock_process_region_outbox.call_count
- # Has rescheduled all objects into the future.
- with freeze_time(start_time):
- ensure_converged()
+ assert last_call_count == 2
- # Next would run the original rescheduled org1 entry
- with freeze_time(start_time + timedelta(minutes=10)):
- run_with_error()
- assert_called_for_org(10001)
- ensure_converged()
+ def test_region_sharding_keys(self):
+ org1 = Factories.create_organization(no_mapping=True)
+ org2 = Factories.create_organization(no_mapping=True)
- # Concurrently added items still follow the largest retry schedule
- Organization.outbox_for_update(10002).save()
- ensure_converged()
+ Organization.outbox_for_update(org1.id).save()
+ Organization.outbox_for_update(org2.id).save()
+ OrganizationMember(organization_id=org1.id, id=1).outbox_for_update().save()
+ OrganizationMember(organization_id=org2.id, id=2).outbox_for_update().save()
[email protected]_db(transaction=True)
-@region_silo_test(stable=True)
-def test_outbox_converges(task_runner):
- with patch("sentry.models.outbox.process_region_outbox.send") as mock_process_region_outbox:
- Organization.outbox_for_update(10001).save()
- Organization.outbox_for_update(10001).save()
-
- Organization.outbox_for_update(10002).save()
- Organization.outbox_for_update(10002).save()
-
- last_call_count = 0
- while True:
- with task_runner():
- enqueue_outbox_jobs()
- if last_call_count == mock_process_region_outbox.call_count:
- break
- last_call_count = mock_process_region_outbox.call_count
-
- assert last_call_count == 2
+ shards = {
+ (row["shard_scope"], row["shard_identifier"])
+ for row in RegionOutbox.find_scheduled_shards()
+ }
+ assert shards == {
+ (OutboxScope.ORGANIZATION_SCOPE.value, org1.id),
+ (OutboxScope.ORGANIZATION_SCOPE.value, org2.id),
+ }
diff --git a/tests/sentry/receivers/outbox/test_control.py b/tests/sentry/receivers/outbox/test_control.py
new file mode 100644
index 00000000000000..616fce5b249215
--- /dev/null
+++ b/tests/sentry/receivers/outbox/test_control.py
@@ -0,0 +1,118 @@
+from unittest.mock import patch
+
+import responses
+from django.test import RequestFactory, override_settings
+from pytest import raises
+from rest_framework import status
+
+from sentry.models.apiapplication import ApiApplication
+from sentry.models.integrations.integration import Integration
+from sentry.models.integrations.organization_integration import OrganizationIntegration
+from sentry.models.integrations.sentry_app_installation import SentryAppInstallation
+from sentry.models.outbox import ControlOutbox, WebhookProviderIdentifier
+from sentry.models.user import User
+from sentry.receivers.outbox.control import (
+ process_api_application_updates,
+ process_async_webhooks,
+ process_integration_updates,
+ process_organization_integration_update,
+ process_sentry_app_installation_updates,
+ process_user_updates,
+)
+from sentry.shared_integrations.exceptions.base import ApiError
+from sentry.silo.base import SiloMode
+from sentry.testutils import TestCase
+from sentry.testutils.silo import control_silo_test
+from sentry.types.region import Region, RegionCategory
+
+
+@control_silo_test(stable=True)
+class ProcessControlOutboxTest(TestCase):
+ identifier = 1
+ region = Region("eu", 1, "http://eu.testserver", RegionCategory.MULTI_TENANT)
+ region_config = (region,)
+
+ @patch("sentry.receivers.outbox.control.maybe_process_tombstone")
+ def test_process_user_updates(self, mock_maybe_process):
+ process_user_updates(object_identifier=self.identifier)
+ mock_maybe_process.assert_called_with(User, self.identifier)
+
+ @patch("sentry.receivers.outbox.control.maybe_process_tombstone")
+ def test_process_integration_updatess(self, mock_maybe_process):
+ process_integration_updates(object_identifier=self.identifier)
+ mock_maybe_process.assert_called_with(Integration, self.identifier)
+
+ @patch("sentry.receivers.outbox.control.maybe_process_tombstone")
+ def test_process_api_application_updates(self, mock_maybe_process):
+ process_api_application_updates(object_identifier=self.identifier)
+ mock_maybe_process.assert_called_with(ApiApplication, self.identifier)
+
+ @patch("sentry.receivers.outbox.control.maybe_process_tombstone")
+ def test_process_sentry_app_installation_updates(self, mock_maybe_process):
+ process_sentry_app_installation_updates(object_identifier=self.identifier)
+ mock_maybe_process.assert_called_with(SentryAppInstallation, self.identifier)
+
+ @patch("sentry.receivers.outbox.control.maybe_process_tombstone")
+ def test_process_organization_integration_update(self, mock_maybe_process):
+ process_organization_integration_update(object_identifier=self.identifier)
+ mock_maybe_process.assert_called_with(OrganizationIntegration, self.identifier)
+
+ @responses.activate
+ @override_settings(SENTRY_REGION_CONFIG=region_config)
+ def test_process_async_webhooks_success(self):
+ request = RequestFactory().post(
+ "/extensions/github/webhook/",
+ data={"installation": {"id": "github:1"}},
+ content_type="application/json",
+ HTTP_X_GITHUB_EMOTICON=">:^]",
+ )
+ [outbox] = ControlOutbox.for_webhook_update(
+ webhook_identifier=WebhookProviderIdentifier.GITHUB,
+ region_names=[self.region.name],
+ request=request,
+ )
+ outbox.save()
+ outbox.refresh_from_db()
+
+ mock_response = responses.add(
+ request.method,
+ f"{self.region.address}{request.path}",
+ status=status.HTTP_200_OK,
+ )
+ process_async_webhooks(payload=outbox.payload, region_name=self.region.name)
+ request_claim = (
+ mock_response.call_count == 1
+ if SiloMode.get_current_mode() == SiloMode.CONTROL
+ else mock_response.call_count == 0
+ )
+ assert request_claim
+
+ @responses.activate
+ @override_settings(SENTRY_REGION_CONFIG=region_config)
+ def test_process_async_webhooks_failure(self):
+ request = RequestFactory().post(
+ "/extensions/github/webhook/",
+ data={"installation": {"id": "github:1"}},
+ content_type="application/json",
+ HTTP_X_GITHUB_EMOTICON=">:^]",
+ )
+ [outbox] = ControlOutbox.for_webhook_update(
+ webhook_identifier=WebhookProviderIdentifier.GITHUB,
+ region_names=[self.region.name],
+ request=request,
+ )
+ outbox.save()
+ outbox.refresh_from_db()
+
+ mock_response = responses.add(
+ request.method,
+ f"{self.region.address}{request.path}",
+ status=status.HTTP_504_GATEWAY_TIMEOUT,
+ )
+ if SiloMode.get_current_mode() == SiloMode.CONTROL:
+ with raises(ApiError):
+ process_async_webhooks(payload=outbox.payload, region_name=self.region.name)
+ assert mock_response.call_count == 1
+ else:
+ process_async_webhooks(payload=outbox.payload, region_name=self.region.name)
+ assert mock_response.call_count == 0
|
fabf6eb10064813fa0c68dec4a1302155f49c32b
|
2024-04-26 20:09:10
|
Alex Zaslavsky
|
fix(backup): Improve race detection and logging (#69745)
| false
|
Improve race detection and logging (#69745)
|
fix
|
diff --git a/src/sentry/services/hybrid_cloud/import_export/impl.py b/src/sentry/services/hybrid_cloud/import_export/impl.py
index 6653672d0d7acd..9f7b44b463985f 100644
--- a/src/sentry/services/hybrid_cloud/import_export/impl.py
+++ b/src/sentry/services/hybrid_cloud/import_export/impl.py
@@ -3,6 +3,7 @@
# in modules such as this one where hybrid cloud data models or service classes are
# defined, because we want to reflect on type annotations and avoid forward references.
+import logging
import traceback
import sentry_sdk
@@ -47,6 +48,8 @@
from sentry.services.hybrid_cloud.import_export.service import ImportExportService
from sentry.silo.base import SiloMode
+logger = logging.getLogger(__name__)
+
def get_existing_import_chunk(
model_name: NormalizedModelName,
@@ -160,6 +163,12 @@ def import_by_model(
else RegionImportChunk
)
+ extra = {
+ "model_name": batch_model_name,
+ "import_uuid": import_flags.import_uuid,
+ "min_ordinal": min_ordinal,
+ }
+
try:
using = router.db_for_write(model)
with transaction.atomic(using=using):
@@ -177,6 +186,7 @@ def import_by_model(
batch_model_name, import_flags, import_chunk_type, min_ordinal
)
if existing_import_chunk is not None:
+ logger.info("import_by_model.already_imported", extra)
return existing_import_chunk
ok_relocation_scopes = import_scope.value
@@ -321,6 +331,7 @@ def import_by_model(
else:
RegionImportChunk(**import_chunk_args).save()
+ logger.info("import_by_model.successfully_imported", extra)
return RpcImportOk(
mapped_pks=RpcPrimaryKeyMap.into_rpc(out_pk_map),
min_ordinal=min_ordinal,
@@ -344,16 +355,18 @@ def import_by_model(
# description from postgres but... ¯\_(ツ)_/¯.
if len(e.args) > 0:
desc = str(e.args[0])
- if desc.startswith("UniqueViolation") and import_chunk_type._meta.db_table in desc:
+
+ # Any `UniqueViolation` indicates the possibility that we've lost a race. Check for
+ # this explicitly by seeing if an `ImportChunk` with a matching unique signature has
+ # been written to the database already.
+ if desc.startswith("UniqueViolation"):
try:
existing_import_chunk = get_existing_import_chunk(
batch_model_name, import_flags, import_chunk_type, min_ordinal
)
- if existing_import_chunk is None:
- raise RuntimeError(
- f"Erroneous import chunk unique collision for identifier: {(import_flags.import_uuid, batch_model_name, min_ordinal)}"
- )
- return existing_import_chunk
+ if existing_import_chunk is not None:
+ logger.warning("import_by_model.lost_import_race", extra)
+ return existing_import_chunk
except Exception:
sentry_sdk.capture_exception()
return RpcImportError(
|
b543bf46377d00db7d47c72a564eb789427bc898
|
2022-05-05 14:30:19
|
Evan Purkhiser
|
ref(js): Avoid import * as React in simple Components (#34267)
| false
|
Avoid import * as React in simple Components (#34267)
|
ref
|
diff --git a/static/app/components/acl/access.tsx b/static/app/components/acl/access.tsx
index f0d760fd41effc..2341e5234aaa44 100644
--- a/static/app/components/acl/access.tsx
+++ b/static/app/components/acl/access.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import Alert from 'sentry/components/alert';
import {t} from 'sentry/locale';
@@ -71,7 +71,7 @@ type Props = {
/**
* Component to handle access restrictions.
*/
-class Access extends React.Component<Props> {
+class Access extends Component<Props> {
static defaultProps = defaultProps;
render() {
diff --git a/static/app/components/acl/feature.tsx b/static/app/components/acl/feature.tsx
index a81a355b775ac9..4e5827ace7e2ce 100644
--- a/static/app/components/acl/feature.tsx
+++ b/static/app/components/acl/feature.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import HookStore from 'sentry/stores/hookStore';
import {Config, Organization, Project} from 'sentry/types';
@@ -102,7 +102,7 @@ type AllFeatures = {
/**
* Component to handle feature flags.
*/
-class Feature extends React.Component<Props> {
+class Feature extends Component<Props> {
static defaultProps = {
renderDisabled: false,
requireAll: true,
diff --git a/static/app/components/actions/resolve.tsx b/static/app/components/actions/resolve.tsx
index 16a7d9557c0a50..c5e50c61533cbf 100644
--- a/static/app/components/actions/resolve.tsx
+++ b/static/app/components/actions/resolve.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import {openModal} from 'sentry/actionCreators/modal';
@@ -41,7 +41,7 @@ type Props = {
shouldConfirm?: boolean;
} & Partial<typeof defaultProps>;
-class ResolveActions extends React.Component<Props> {
+class ResolveActions extends Component<Props> {
static defaultProps = defaultProps;
handleAnotherExistingReleaseResolution(statusDetails: ResolutionStatusDetails) {
diff --git a/static/app/components/activity/note/input.tsx b/static/app/components/activity/note/input.tsx
index 2e740a383856a1..d66a81e7a5af9b 100644
--- a/static/app/components/activity/note/input.tsx
+++ b/static/app/components/activity/note/input.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {Mention, MentionsInput, MentionsInputProps} from 'react-mentions';
import {withTheme} from '@emotion/react';
import styled from '@emotion/styled';
@@ -52,7 +52,7 @@ type State = {
value: string;
};
-class NoteInputComponent extends React.Component<Props, State> {
+class NoteInputComponent extends Component<Props, State> {
state: State = {
preview: false,
value: this.props.text || '',
@@ -264,7 +264,7 @@ type MentionablesChildFunc = Parameters<
React.ComponentProps<typeof Mentionables>['children']
>[0];
-class NoteInputContainer extends React.Component<NoteInputContainerProps> {
+class NoteInputContainer extends Component<NoteInputContainerProps> {
static defaultProps = defaultProps;
renderInput = ({members, teams}: MentionablesChildFunc) => {
diff --git a/static/app/components/activity/note/inputWithStorage.tsx b/static/app/components/activity/note/inputWithStorage.tsx
index a1ec500ecfa725..3fcc7ef4a4de28 100644
--- a/static/app/components/activity/note/inputWithStorage.tsx
+++ b/static/app/components/activity/note/inputWithStorage.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import * as Sentry from '@sentry/react';
import debounce from 'lodash/debounce';
@@ -24,7 +24,7 @@ type Props = {
} & InputProps &
typeof defaultProps;
-class NoteInputWithStorage extends React.Component<Props> {
+class NoteInputWithStorage extends Component<Props> {
static defaultProps = defaultProps;
fetchFromStorage() {
diff --git a/static/app/components/assigneeSelector.tsx b/static/app/components/assigneeSelector.tsx
index 508205f5d03374..31744e03e7f539 100644
--- a/static/app/components/assigneeSelector.tsx
+++ b/static/app/components/assigneeSelector.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import {assignToActor, assignToUser, clearAssignment} from 'sentry/actionCreators/group';
@@ -58,7 +58,7 @@ type State = {
suggestedOwners?: SuggestedOwner[] | null;
};
-class AssigneeSelector extends React.Component<Props, State> {
+class AssigneeSelector extends Component<Props, State> {
static defaultProps = {
size: 20,
};
diff --git a/static/app/components/asyncComponentSearchInput.tsx b/static/app/components/asyncComponentSearchInput.tsx
index 898e065989af7d..5a96d835dc8b7a 100644
--- a/static/app/components/asyncComponentSearchInput.tsx
+++ b/static/app/components/asyncComponentSearchInput.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {withRouter, WithRouterProps} from 'react-router';
import styled from '@emotion/styled';
import debounce from 'lodash/debounce';
@@ -59,7 +59,7 @@ type State = {
*
* It probably doesn't make too much sense outside of an AsyncComponent atm.
*/
-class AsyncComponentSearchInput extends React.Component<Props, State> {
+class AsyncComponentSearchInput extends Component<Props, State> {
static defaultProps: DefaultProps = {
placeholder: t('Search...'),
debounceWait: 200,
diff --git a/static/app/components/avatar/actorAvatar.tsx b/static/app/components/avatar/actorAvatar.tsx
index 5420696ece9bd9..d37abf3d1d12c2 100644
--- a/static/app/components/avatar/actorAvatar.tsx
+++ b/static/app/components/avatar/actorAvatar.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import * as Sentry from '@sentry/react';
import TeamAvatar from 'sentry/components/avatar/teamAvatar';
@@ -26,7 +26,7 @@ type Props = DefaultProps & {
tooltipOptions?: Omit<React.ComponentProps<typeof Tooltip>, 'children' | 'title'>;
};
-class ActorAvatar extends React.Component<Props> {
+class ActorAvatar extends Component<Props> {
static defaultProps: DefaultProps = {
size: 24,
hasTooltip: true,
diff --git a/static/app/components/avatar/baseAvatar.tsx b/static/app/components/avatar/baseAvatar.tsx
index 5b3bd1cd2b90e8..66d369518b2ddd 100644
--- a/static/app/components/avatar/baseAvatar.tsx
+++ b/static/app/components/avatar/baseAvatar.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import classNames from 'classnames';
import * as qs from 'query-string';
@@ -111,7 +111,7 @@ type State = {
showBackupAvatar: boolean;
};
-class BaseAvatar extends React.Component<Props, State> {
+class BaseAvatar extends Component<Props, State> {
static defaultProps = defaultProps;
constructor(props: Props) {
diff --git a/static/app/components/avatar/userAvatar.tsx b/static/app/components/avatar/userAvatar.tsx
index e512409315f0e7..417204abbf7764 100644
--- a/static/app/components/avatar/userAvatar.tsx
+++ b/static/app/components/avatar/userAvatar.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import BaseAvatar from 'sentry/components/avatar/baseAvatar';
import {Actor, AvatarUser} from 'sentry/types';
@@ -25,7 +25,7 @@ function isActor(maybe: AvatarUser | Actor): maybe is Actor {
return typeof (maybe as AvatarUser).email === 'undefined';
}
-class UserAvatar extends React.Component<Props> {
+class UserAvatar extends Component<Props> {
static defaultProps = defaultProps;
getType = (user: AvatarUser | Actor, gravatar: boolean | undefined) => {
diff --git a/static/app/components/avatarChooser.tsx b/static/app/components/avatarChooser.tsx
index d9784d3937c11c..1af4af5e7ab094 100644
--- a/static/app/components/avatarChooser.tsx
+++ b/static/app/components/avatarChooser.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
@@ -59,7 +59,7 @@ type State = {
savedDataUrl?: string | null;
};
-class AvatarChooser extends React.Component<Props, State> {
+class AvatarChooser extends Component<Props, State> {
static defaultProps: DefaultProps = {
allowGravatar: true,
allowLetter: true,
diff --git a/static/app/components/bases/pluginComponentBase.tsx b/static/app/components/bases/pluginComponentBase.tsx
index 886eaa141e8270..f4b4084ff67852 100644
--- a/static/app/components/bases/pluginComponentBase.tsx
+++ b/static/app/components/bases/pluginComponentBase.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import isFunction from 'lodash/isFunction';
import {
@@ -24,7 +24,7 @@ type State = {state: GenericFieldProps['formState']};
class PluginComponentBase<
P extends Props = Props,
S extends State = State
-> extends React.Component<P, S> {
+> extends Component<P, S> {
constructor(props: P, context: any) {
super(props, context);
diff --git a/static/app/components/bulkController/index.tsx b/static/app/components/bulkController/index.tsx
index 1ff86f359f9073..3a2564028f67b3 100644
--- a/static/app/components/bulkController/index.tsx
+++ b/static/app/components/bulkController/index.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import intersection from 'lodash/intersection';
import isEqual from 'lodash/isEqual';
import uniq from 'lodash/uniq';
@@ -72,7 +72,7 @@ type Props = {
onChange?: (props: State) => void;
};
-class BulkController extends React.Component<Props, State> {
+class BulkController extends Component<Props, State> {
state: State = this.getInitialState();
getInitialState() {
diff --git a/static/app/components/charts/barChartZoom.tsx b/static/app/components/charts/barChartZoom.tsx
index 4915d865d93fa9..baabd2b46b259e 100644
--- a/static/app/components/charts/barChartZoom.tsx
+++ b/static/app/components/charts/barChartZoom.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {browserHistory} from 'react-router';
import {Location} from 'history';
@@ -64,7 +64,7 @@ type Props = {
onHistoryPush?: (start: number, end: number) => void;
};
-class BarChartZoom extends React.Component<Props> {
+class BarChartZoom extends Component<Props> {
zooming: (() => void) | null = null;
/**
diff --git a/static/app/components/charts/chartZoom.tsx b/static/app/components/charts/chartZoom.tsx
index e03fc80869701b..b6a290f30d34d5 100644
--- a/static/app/components/charts/chartZoom.tsx
+++ b/static/app/components/charts/chartZoom.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {InjectedRouter} from 'react-router';
import type {
DataZoomComponentOption,
@@ -79,7 +79,7 @@ type Props = {
* This also is very tightly coupled with the Global Selection Header. We can make it more
* generic if need be in the future.
*/
-class ChartZoom extends React.Component<Props> {
+class ChartZoom extends Component<Props> {
constructor(props: Props) {
super(props);
diff --git a/static/app/components/charts/percentageAreaChart.tsx b/static/app/components/charts/percentageAreaChart.tsx
index 4dd6804c43081d..56f171cd1e6409 100644
--- a/static/app/components/charts/percentageAreaChart.tsx
+++ b/static/app/components/charts/percentageAreaChart.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import type {LineSeriesOption} from 'echarts';
import moment from 'moment';
@@ -29,7 +29,7 @@ type Props = Omit<ChartProps, 'series'> &
*
* See https://exceljet.net/chart-type/100-stacked-bar-chart
*/
-export default class PercentageAreaChart extends React.Component<Props> {
+export default class PercentageAreaChart extends Component<Props> {
static defaultProps: DefaultProps = {
// TODO(billyvg): Move these into BaseChart? or get rid completely
getDataItemName: ({name}) => name,
diff --git a/static/app/components/charts/releaseSeries.tsx b/static/app/components/charts/releaseSeries.tsx
index dfd3605981dceb..51a9fd83581b78 100644
--- a/static/app/components/charts/releaseSeries.tsx
+++ b/static/app/components/charts/releaseSeries.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {withRouter, WithRouterProps} from 'react-router';
import {withTheme} from '@emotion/react';
import {Query} from 'history';
@@ -85,7 +85,7 @@ type State = {
releases: ReleaseMetaBasic[] | null;
};
-class ReleaseSeries extends React.Component<Props, State> {
+class ReleaseSeries extends Component<Props, State> {
state: State = {
releases: null,
releaseSeries: [],
diff --git a/static/app/components/charts/sessionsRequest.tsx b/static/app/components/charts/sessionsRequest.tsx
index f329eca5e7404b..691f4aecf96cfe 100644
--- a/static/app/components/charts/sessionsRequest.tsx
+++ b/static/app/components/charts/sessionsRequest.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import isEqual from 'lodash/isEqual';
import omitBy from 'lodash/omitBy';
@@ -42,7 +42,7 @@ type State = {
response: SessionApiResponse | null;
};
-class SessionsRequest extends React.Component<Props, State> {
+class SessionsRequest extends Component<Props, State> {
state: State = {
reloading: false,
errored: false,
diff --git a/static/app/components/charts/stackedAreaChart.tsx b/static/app/components/charts/stackedAreaChart.tsx
index baadbd5c475f73..33995f9e231ac7 100644
--- a/static/app/components/charts/stackedAreaChart.tsx
+++ b/static/app/components/charts/stackedAreaChart.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {AreaChart} from 'sentry/components/charts/areaChart';
@@ -6,7 +6,7 @@ type AreaChartProps = React.ComponentProps<typeof AreaChart>;
type Props = Omit<AreaChartProps, 'stacked' | 'ref'>;
-class StackedAreaChart extends React.Component<Props> {
+class StackedAreaChart extends Component<Props> {
render() {
return <AreaChart tooltip={{filter: val => val > 0}} {...this.props} stacked />;
}
diff --git a/static/app/components/customResolutionModal.tsx b/static/app/components/customResolutionModal.tsx
index 88b68cc3a4f07b..dc9179d27d9ede 100644
--- a/static/app/components/customResolutionModal.tsx
+++ b/static/app/components/customResolutionModal.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {components as selectComponents} from 'react-select';
import {ModalRenderProps} from 'sentry/actionCreators/modal';
@@ -38,7 +38,7 @@ function VersionOption({
);
}
-class CustomResolutionModal extends React.Component<Props, State> {
+class CustomResolutionModal extends Component<Props, State> {
state: State = {
version: '',
};
diff --git a/static/app/components/dashboards/issueWidgetQueriesForm.tsx b/static/app/components/dashboards/issueWidgetQueriesForm.tsx
index b82e03cf6a6bb8..3ed76a8e1ef369 100644
--- a/static/app/components/dashboards/issueWidgetQueriesForm.tsx
+++ b/static/app/components/dashboards/issueWidgetQueriesForm.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import cloneDeep from 'lodash/cloneDeep';
@@ -37,7 +37,7 @@ type State = {
* Contain widget queries interactions and signal changes via the onChange
* callback. This component's state should live in the parent.
*/
-class IssueWidgetQueriesForm extends React.Component<Props, State> {
+class IssueWidgetQueriesForm extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
diff --git a/static/app/components/dashboards/widgetQueriesForm.tsx b/static/app/components/dashboards/widgetQueriesForm.tsx
index 88d9de6924e920..c56237ef02c525 100644
--- a/static/app/components/dashboards/widgetQueriesForm.tsx
+++ b/static/app/components/dashboards/widgetQueriesForm.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import cloneDeep from 'lodash/cloneDeep';
@@ -93,7 +93,7 @@ type Props = {
* Contain widget queries interactions and signal changes via the onChange
* callback. This component's state should live in the parent.
*/
-class WidgetQueriesForm extends React.Component<Props> {
+class WidgetQueriesForm extends Component<Props> {
componentWillUnmount() {
window.clearTimeout(this.blurTimeout);
}
diff --git a/static/app/components/deprecatedforms/form.tsx b/static/app/components/deprecatedforms/form.tsx
index d667c1db956ba4..e1c3eb6d972beb 100644
--- a/static/app/components/deprecatedforms/form.tsx
+++ b/static/app/components/deprecatedforms/form.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import isEqual from 'lodash/isEqual';
@@ -44,7 +44,7 @@ export type Context = FormContextData;
class Form<
Props extends FormProps = FormProps,
State extends FormClassState = FormClassState
-> extends React.Component<Props, State> {
+> extends Component<Props, State> {
static defaultProps = {
cancelLabel: t('Cancel'),
submitLabel: t('Save Changes'),
diff --git a/static/app/components/errorBoundary.tsx b/static/app/components/errorBoundary.tsx
index 05c87a4d7124f9..20da77023859b5 100644
--- a/static/app/components/errorBoundary.tsx
+++ b/static/app/components/errorBoundary.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {browserHistory} from 'react-router';
import styled from '@emotion/styled';
import * as Sentry from '@sentry/react';
@@ -32,7 +32,7 @@ function getExclamation() {
return exclamation[Math.floor(Math.random() * exclamation.length)];
}
-class ErrorBoundary extends React.Component<Props, State> {
+class ErrorBoundary extends Component<Props, State> {
static defaultProps: DefaultProps = {
mini: false,
};
diff --git a/static/app/components/errors/detailedError.tsx b/static/app/components/errors/detailedError.tsx
index 93c06f2f37069f..7ad96c19bf4361 100644
--- a/static/app/components/errors/detailedError.tsx
+++ b/static/app/components/errors/detailedError.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import * as Sentry from '@sentry/react';
import classNames from 'classnames';
@@ -34,7 +34,7 @@ function openFeedback(e: React.MouseEvent) {
Sentry.showReportDialog();
}
-class DetailedError extends React.Component<Props> {
+class DetailedError extends Component<Props> {
static defaultProps: DefaultProps = {
hideSupportLinks: false,
};
diff --git a/static/app/components/events/contexts/redux.tsx b/static/app/components/events/contexts/redux.tsx
index 2a7693cca7ff88..5549539a579139 100644
--- a/static/app/components/events/contexts/redux.tsx
+++ b/static/app/components/events/contexts/redux.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import ClippedBox from 'sentry/components/clippedBox';
import ContextBlock from 'sentry/components/events/contexts/contextBlock';
@@ -12,7 +12,7 @@ type Props = {
data: Record<string, any>;
};
-class ReduxContextType extends React.Component<Props> {
+class ReduxContextType extends Component<Props> {
getKnownData(): KeyValueListData {
return [
{
diff --git a/static/app/components/events/contexts/state.tsx b/static/app/components/events/contexts/state.tsx
index 3a0bc0d2491d17..ea17f585989f65 100644
--- a/static/app/components/events/contexts/state.tsx
+++ b/static/app/components/events/contexts/state.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import upperFirst from 'lodash/upperFirst';
import ClippedBox from 'sentry/components/clippedBox';
@@ -21,7 +21,7 @@ type Props = {
};
};
-class StateContextType extends React.Component<Props> {
+class StateContextType extends Component<Props> {
getStateTitle(name: string, type?: string) {
return `${name}${type ? ` (${upperFirst(type)})` : ''}`;
}
diff --git a/static/app/components/events/groupingInfo/groupingVariant.tsx b/static/app/components/events/groupingInfo/groupingVariant.tsx
index 41ca18c857c0f6..da79c009cbb67e 100644
--- a/static/app/components/events/groupingInfo/groupingVariant.tsx
+++ b/static/app/components/events/groupingInfo/groupingVariant.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import capitalize from 'lodash/capitalize';
@@ -65,7 +65,7 @@ function addFingerprintInfo(data: VariantData, variant: EventGroupVariant) {
}
}
-class GroupVariant extends React.Component<Props, State> {
+class GroupVariant extends Component<Props, State> {
state: State = {
showNonContributing: false,
};
diff --git a/static/app/components/events/interfaces/debugMeta-v2/debugImageDetails/candidates.tsx b/static/app/components/events/interfaces/debugMeta-v2/debugImageDetails/candidates.tsx
index 8147bb32c5cf8c..532615270c873d 100644
--- a/static/app/components/events/interfaces/debugMeta-v2/debugImageDetails/candidates.tsx
+++ b/static/app/components/events/interfaces/debugMeta-v2/debugImageDetails/candidates.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import debounce from 'lodash/debounce';
import isEqual from 'lodash/isEqual';
@@ -49,7 +49,7 @@ type State = {
searchTerm: string;
};
-class Candidates extends React.Component<Props, State> {
+class Candidates extends Component<Props, State> {
state: State = {
searchTerm: '',
filterOptions: {},
diff --git a/static/app/components/events/interfaces/frame/line.tsx b/static/app/components/events/interfaces/frame/line.tsx
index fed5276769ce2b..f7609cf82db50d 100644
--- a/static/app/components/events/interfaces/frame/line.tsx
+++ b/static/app/components/events/interfaces/frame/line.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import classNames from 'classnames';
import scrollToElement from 'scroll-to-element';
@@ -80,7 +80,7 @@ function makeFilter(
return addr;
}
-export class Line extends React.Component<Props, State> {
+export class Line extends Component<Props, State> {
static defaultProps = {
isExpanded: false,
emptySourceNotation: false,
diff --git a/static/app/components/events/interfaces/frame/packageLink.tsx b/static/app/components/events/interfaces/frame/packageLink.tsx
index e02dadb200078a..3cb5bf7a728caf 100644
--- a/static/app/components/events/interfaces/frame/packageLink.tsx
+++ b/static/app/components/events/interfaces/frame/packageLink.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import {trimPackage} from 'sentry/components/events/interfaces/frame/utils';
@@ -20,7 +20,7 @@ type Props = {
isHoverPreviewed?: boolean;
};
-class PackageLink extends React.Component<Props> {
+class PackageLink extends Component<Props> {
handleClick = (event: React.MouseEvent<HTMLAnchorElement>) => {
const {isClickable, onClick} = this.props;
diff --git a/static/app/components/events/interfaces/request.tsx b/static/app/components/events/interfaces/request.tsx
index 91b02a871960d6..c5e2cfdb65921f 100644
--- a/static/app/components/events/interfaces/request.tsx
+++ b/static/app/components/events/interfaces/request.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import Button from 'sentry/components/button';
@@ -24,7 +24,7 @@ type State = {
view: string;
};
-class RequestInterface extends React.Component<Props, State> {
+class RequestInterface extends Component<Props, State> {
state: State = {
view: 'formatted',
};
diff --git a/static/app/components/events/interfaces/spans/dragManager.tsx b/static/app/components/events/interfaces/spans/dragManager.tsx
index 3c4a4c5c7c10f6..8ec16a9f8bf4e2 100644
--- a/static/app/components/events/interfaces/spans/dragManager.tsx
+++ b/static/app/components/events/interfaces/spans/dragManager.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {clamp, rectOfContent} from 'sentry/components/performance/waterfall/utils';
import {PerformanceInteraction} from 'sentry/utils/performanceForSentry';
@@ -70,7 +70,7 @@ type DragManagerState = {
windowSelectionSize: number;
};
-class DragManager extends React.Component<DragManagerProps, DragManagerState> {
+class DragManager extends Component<DragManagerProps, DragManagerState> {
state: DragManagerState = {
// draggable handles
diff --git a/static/app/components/events/interfaces/spans/spanTree.tsx b/static/app/components/events/interfaces/spans/spanTree.tsx
index fbc3ce00849c50..757acdee6bb5f9 100644
--- a/static/app/components/events/interfaces/spans/spanTree.tsx
+++ b/static/app/components/events/interfaces/spans/spanTree.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import isEqual from 'lodash/isEqual';
@@ -32,7 +32,7 @@ type PropType = ScrollbarManagerChildrenProps & {
waterfallModel: WaterfallModel;
};
-class SpanTree extends React.Component<PropType> {
+class SpanTree extends Component<PropType> {
componentDidMount() {
setSpansOnTransaction(this.props.spans.length);
}
diff --git a/static/app/components/eventsTable/eventsTableRow.tsx b/static/app/components/eventsTable/eventsTableRow.tsx
index e5ee928d92061c..c17ee322a3381b 100644
--- a/static/app/components/eventsTable/eventsTableRow.tsx
+++ b/static/app/components/eventsTable/eventsTableRow.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import UserAvatar from 'sentry/components/avatar/userAvatar';
import DateTime from 'sentry/components/dateTime';
@@ -20,7 +20,7 @@ type Props = {
hasUser?: boolean;
} & React.HTMLAttributes<HTMLDivElement>;
-class EventsTableRow extends React.Component<Props> {
+class EventsTableRow extends Component<Props> {
renderCrashFileLink() {
const {event, projectId} = this.props;
if (!event.crashFile) {
diff --git a/static/app/components/forms/booleanField.tsx b/static/app/components/forms/booleanField.tsx
index c9e14f1fa7a562..630070e5fd51b2 100644
--- a/static/app/components/forms/booleanField.tsx
+++ b/static/app/components/forms/booleanField.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import Confirm from 'sentry/components/confirm';
import InputField, {InputFieldProps, onEvent} from 'sentry/components/forms/inputField';
@@ -11,7 +11,7 @@ export interface BooleanFieldProps extends InputFieldProps {
};
}
-export default class BooleanField extends React.Component<BooleanFieldProps> {
+export default class BooleanField extends Component<BooleanFieldProps> {
coerceValue(value: any) {
return !!value;
}
diff --git a/static/app/components/forms/controls/multipleCheckbox.tsx b/static/app/components/forms/controls/multipleCheckbox.tsx
index 0f0fb950f04fae..54b14189ed0c3e 100644
--- a/static/app/components/forms/controls/multipleCheckbox.tsx
+++ b/static/app/components/forms/controls/multipleCheckbox.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import {Choices} from 'sentry/types';
@@ -30,7 +30,7 @@ type Props = {
onChange?: (value: SelectedValue, event: React.ChangeEvent<HTMLInputElement>) => void;
};
-class MultipleCheckbox extends React.Component<Props> {
+class MultipleCheckbox extends Component<Props> {
onChange = (selectedValue: string | number, e: React.ChangeEvent<HTMLInputElement>) => {
const {value, onChange} = this.props;
let newValue: SelectedValue = [];
diff --git a/static/app/components/forms/field/index.tsx b/static/app/components/forms/field/index.tsx
index e2f243dcbe7562..45286eb56878d1 100644
--- a/static/app/components/forms/field/index.tsx
+++ b/static/app/components/forms/field/index.tsx
@@ -1,11 +1,4 @@
-/**
- * A component to render a Field (i.e. label + help + form "control"),
- * generally inside of a Panel.
- *
- * This is unconnected to any Form state
- */
-
-import * as React from 'react';
+import {Component} from 'react';
import ControlState, {
ControlStateProps,
@@ -108,7 +101,13 @@ interface ChildRenderProps extends Omit<FieldProps, 'className' | 'disabled'> {
disabled?: boolean;
}
-class Field extends React.Component<FieldProps> {
+/**
+ * A component to render a Field (i.e. label + help + form "control"),
+ * generally inside of a Panel.
+ *
+ * This is unconnected to any Form state
+ */
+class Field extends Component<FieldProps> {
static defaultProps = {
alignRight: false,
inline: true,
diff --git a/static/app/components/forms/form.tsx b/static/app/components/forms/form.tsx
index aba718d4b24d89..cd049fabfed129 100644
--- a/static/app/components/forms/form.tsx
+++ b/static/app/components/forms/form.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import {Observer} from 'mobx-react';
@@ -86,7 +86,7 @@ type Props = {
submitPriority?: ButtonProps['priority'];
} & Pick<FormOptions, 'onSubmitSuccess' | 'onSubmitError' | 'onFieldChange'>;
-export default class Form extends React.Component<Props> {
+export default class Form extends Component<Props> {
constructor(props: Props, context: FormContextData) {
super(props, context);
const {
diff --git a/static/app/components/forms/formPanel.tsx b/static/app/components/forms/formPanel.tsx
index 9d0b6ae31f8911..314024be3bed68 100644
--- a/static/app/components/forms/formPanel.tsx
+++ b/static/app/components/forms/formPanel.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import FieldFromConfig from 'sentry/components/forms/fieldFromConfig';
@@ -55,7 +55,7 @@ type State = {
collapsed: boolean;
};
-export default class FormPanel extends React.Component<Props, State> {
+export default class FormPanel extends Component<Props, State> {
static defaultProps: DefaultProps = {
additionalFieldProps: {},
};
diff --git a/static/app/components/forms/radioField.tsx b/static/app/components/forms/radioField.tsx
index bae54b2136a3ce..5194f05f041361 100644
--- a/static/app/components/forms/radioField.tsx
+++ b/static/app/components/forms/radioField.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import RadioGroup, {RadioGroupProps} from 'sentry/components/forms/controls/radioGroup';
import InputField, {InputFieldProps, onEvent} from 'sentry/components/forms/inputField';
@@ -8,7 +8,7 @@ export interface RadioFieldProps extends Omit<InputFieldProps, 'type'> {
orientInline?: RadioGroupProps<any>['orientInline'];
}
-class RadioField extends React.Component<RadioFieldProps> {
+class RadioField extends Component<RadioFieldProps> {
onChange = (
id: string,
onChange: onEvent,
diff --git a/static/app/components/forms/selectAsyncField.tsx b/static/app/components/forms/selectAsyncField.tsx
index 3816bc50789d15..0e679c0ea853ff 100644
--- a/static/app/components/forms/selectAsyncField.tsx
+++ b/static/app/components/forms/selectAsyncField.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import InputField, {InputFieldProps} from 'sentry/components/forms/inputField';
import SelectAsyncControl, {
@@ -16,10 +16,7 @@ type SelectAsyncFieldState = {
results: Result[];
latestSelection?: GeneralSelectValue;
};
-class SelectAsyncField extends React.Component<
- SelectAsyncFieldProps,
- SelectAsyncFieldState
-> {
+class SelectAsyncField extends Component<SelectAsyncFieldProps, SelectAsyncFieldState> {
state: SelectAsyncFieldState = {
results: [],
latestSelection: undefined,
diff --git a/static/app/components/forms/selectField.tsx b/static/app/components/forms/selectField.tsx
index 1aacfbf884281f..6b5c81a8e90f0c 100644
--- a/static/app/components/forms/selectField.tsx
+++ b/static/app/components/forms/selectField.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {OptionsType, ValueType} from 'react-select';
import {openConfirmModal} from 'sentry/components/confirm';
@@ -55,9 +55,9 @@ function isArray<T>(maybe: T | OptionsType<T>): maybe is OptionsType<T> {
return Array.isArray(maybe);
}
-export default class SelectField<
- OptionType extends SelectValue<any>
-> extends React.Component<SelectFieldProps<OptionType>> {
+export default class SelectField<OptionType extends SelectValue<any>> extends Component<
+ SelectFieldProps<OptionType>
+> {
static defaultProps = {
allowClear: false,
allowEmpty: false,
diff --git a/static/app/components/forms/sentryProjectSelectorField.tsx b/static/app/components/forms/sentryProjectSelectorField.tsx
index f51fc933f23b6a..bf8a0683140427 100644
--- a/static/app/components/forms/sentryProjectSelectorField.tsx
+++ b/static/app/components/forms/sentryProjectSelectorField.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {components} from 'react-select';
import InputField, {InputFieldProps} from 'sentry/components/forms/inputField';
@@ -23,7 +23,7 @@ interface RenderProps
projects: Project[]; // can't use AvatarProject since we need the ID
}
-class RenderField extends React.Component<RenderProps> {
+class RenderField extends Component<RenderProps> {
static defaultProps = defaultProps;
// need to map the option object to the value
diff --git a/static/app/components/forms/textCopyInput.tsx b/static/app/components/forms/textCopyInput.tsx
index 151eaac3b97bf5..b6df0b0769cf58 100644
--- a/static/app/components/forms/textCopyInput.tsx
+++ b/static/app/components/forms/textCopyInput.tsx
@@ -1,4 +1,4 @@
-import {CSSProperties} from 'react';
+import {Component} from 'react';
import * as React from 'react';
import {findDOMNode} from 'react-dom';
import styled from '@emotion/styled';
@@ -49,10 +49,10 @@ type Props = {
* Always show the ending of a long overflowing text in input
*/
rtl?: boolean;
- style?: CSSProperties;
+ style?: React.CSSProperties;
};
-class TextCopyInput extends React.Component<Props> {
+class TextCopyInput extends Component<Props> {
textRef = React.createRef<HTMLInputElement>();
// Select text when copy button is clicked
diff --git a/static/app/components/gridEditable/sortLink.tsx b/static/app/components/gridEditable/sortLink.tsx
index e561d9a6f5c2ee..240da0e1c13dea 100644
--- a/static/app/components/gridEditable/sortLink.tsx
+++ b/static/app/components/gridEditable/sortLink.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import {LocationDescriptorObject} from 'history';
import omit from 'lodash/omit';
@@ -19,7 +19,7 @@ type Props = {
onClick?: (e: React.MouseEvent<HTMLAnchorElement>) => void;
};
-class SortLink extends React.Component<Props> {
+class SortLink extends Component<Props> {
renderArrow() {
const {direction} = this.props;
if (!direction) {
diff --git a/static/app/components/group/sentryAppExternalIssueActions.tsx b/static/app/components/group/sentryAppExternalIssueActions.tsx
index a4f507e08752be..385643ac38dbf3 100644
--- a/static/app/components/group/sentryAppExternalIssueActions.tsx
+++ b/static/app/components/group/sentryAppExternalIssueActions.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
@@ -36,7 +36,7 @@ type State = {
externalIssue?: PlatformExternalIssue;
};
-class SentryAppExternalIssueActions extends React.Component<Props, State> {
+class SentryAppExternalIssueActions extends Component<Props, State> {
state: State = {
action: 'create',
externalIssue: this.props.externalIssue,
diff --git a/static/app/components/hook.tsx b/static/app/components/hook.tsx
index 64c9182274150a..a1c73ba383920a 100644
--- a/static/app/components/hook.tsx
+++ b/static/app/components/hook.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import HookStore from 'sentry/stores/hookStore';
import {HookName, Hooks} from 'sentry/types/hooks';
@@ -34,7 +34,7 @@ type HookState<H extends HookName> = {
* </Hook>
*/
function Hook<H extends HookName>({name, ...props}: Props<H>) {
- class HookComponent extends React.Component<{}, HookState<H>> {
+ class HookComponent extends Component<{}, HookState<H>> {
static displayName = `Hook(${name})`;
state = {
diff --git a/static/app/components/issueSyncListElement.tsx b/static/app/components/issueSyncListElement.tsx
index c01b571067ab08..1f6690728a9310 100644
--- a/static/app/components/issueSyncListElement.tsx
+++ b/static/app/components/issueSyncListElement.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {ClassNames} from '@emotion/react';
import styled from '@emotion/styled';
import capitalize from 'lodash/capitalize';
@@ -22,7 +22,7 @@ type Props = {
showHoverCard?: boolean;
};
-class IssueSyncListElement extends React.Component<Props> {
+class IssueSyncListElement extends Component<Props> {
isLinked(): boolean {
return !!(this.props.externalIssueLink && this.props.externalIssueId);
}
diff --git a/static/app/components/links/listLink.tsx b/static/app/components/links/listLink.tsx
index 0a18ef352d019f..0e8b0e33f3bce9 100644
--- a/static/app/components/links/listLink.tsx
+++ b/static/app/components/links/listLink.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {Link as RouterLink, withRouter, WithRouterProps} from 'react-router';
import styled from '@emotion/styled';
import classNames from 'classnames';
@@ -28,7 +28,7 @@ type Props = WithRouterProps &
query?: string;
};
-class ListLink extends React.Component<Props> {
+class ListLink extends Component<Props> {
static displayName = 'ListLink';
static defaultProps: DefaultProps = {
diff --git a/static/app/components/loadingError.tsx b/static/app/components/loadingError.tsx
index c4a066d02b185f..89b58c18eb255f 100644
--- a/static/app/components/loadingError.tsx
+++ b/static/app/components/loadingError.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import Alert from 'sentry/components/alert';
@@ -18,7 +18,7 @@ type Props = DefaultProps & {
/**
* Renders an Alert box of type "error". Renders a "Retry" button only if a `onRetry` callback is defined.
*/
-class LoadingError extends React.Component<Props> {
+class LoadingError extends Component<Props> {
static defaultProps: DefaultProps = {
message: t('There was an error loading data.'),
};
diff --git a/static/app/components/modals/inviteMembersModal/inviteRowControl.tsx b/static/app/components/modals/inviteMembersModal/inviteRowControl.tsx
index 4671563f22f2aa..67e331f95998f5 100644
--- a/static/app/components/modals/inviteMembersModal/inviteRowControl.tsx
+++ b/static/app/components/modals/inviteMembersModal/inviteRowControl.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {MultiValueProps, StylesConfig} from 'react-select';
import {withTheme} from '@emotion/react';
@@ -49,7 +49,7 @@ function mapToOptions(values: string[]): SelectOption[] {
return values.map(value => ({value, label: value}));
}
-class InviteRowControl extends React.Component<Props, State> {
+class InviteRowControl extends Component<Props, State> {
state: State = {inputValue: ''};
handleInputChange = (inputValue: string) => {
diff --git a/static/app/components/numberDragControl.tsx b/static/app/components/numberDragControl.tsx
index 3d8a5f1325b389..bf6867a3c9ee32 100644
--- a/static/app/components/numberDragControl.tsx
+++ b/static/app/components/numberDragControl.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import {IconArrow} from 'sentry/icons';
@@ -25,7 +25,7 @@ type State = {
isClicked: boolean;
};
-class NumberDragControl extends React.Component<Props, State> {
+class NumberDragControl extends Component<Props, State> {
state: State = {
isClicked: false,
};
diff --git a/static/app/components/organizations/timeRangeSelector/timePicker.tsx b/static/app/components/organizations/timeRangeSelector/timePicker.tsx
index 1ef8ece17b5548..ae6fd1fae0e004 100644
--- a/static/app/components/organizations/timeRangeSelector/timePicker.tsx
+++ b/static/app/components/organizations/timeRangeSelector/timePicker.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import classNames from 'classnames';
@@ -19,7 +19,7 @@ type State = {
};
const TimePicker = styled(
- class TimePicker extends React.Component<Props, State> {
+ class TimePicker extends Component<Props, State> {
state: State = {
focused: false,
};
diff --git a/static/app/components/repositoryFileSummary.tsx b/static/app/components/repositoryFileSummary.tsx
index f35301bc538828..1f749d3011d664 100644
--- a/static/app/components/repositoryFileSummary.tsx
+++ b/static/app/components/repositoryFileSummary.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import FileChange from 'sentry/components/fileChange';
@@ -34,7 +34,7 @@ type State = {
loading: boolean;
};
-class RepositoryFileSummary extends React.Component<Props, State> {
+class RepositoryFileSummary extends Component<Props, State> {
static defaultProps = {
collapsible: true,
maxWhenCollapsed: 5,
diff --git a/static/app/components/resultGrid.tsx b/static/app/components/resultGrid.tsx
index ffc80096be2864..0d5857d56af7e4 100644
--- a/static/app/components/resultGrid.tsx
+++ b/static/app/components/resultGrid.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {browserHistory} from 'react-router';
import {Location} from 'history';
@@ -20,7 +20,7 @@ type FilterProps = {
value: string;
};
-class Filter extends React.Component<FilterProps> {
+class Filter extends Component<FilterProps> {
getCurrentLabel() {
const selected = this.props.options.find(
item => item[0] === (this.props.value ?? '')
@@ -89,7 +89,7 @@ type SortByProps = {
value: string;
};
-class SortBy extends React.Component<SortByProps> {
+class SortBy extends Component<SortByProps> {
getCurrentSortLabel() {
return this.props.options.find(([value]) => value === this.props.value)?.[1];
}
@@ -169,7 +169,7 @@ type State = {
sortBy: string;
};
-class ResultGrid extends React.Component<Props, State> {
+class ResultGrid extends Component<Props, State> {
static defaultProps: DefaultProps = {
path: '',
endpoint: '',
diff --git a/static/app/components/search/sources/apiSource.tsx b/static/app/components/search/sources/apiSource.tsx
index 80e0a970706495..e994ba1a722a36 100644
--- a/static/app/components/search/sources/apiSource.tsx
+++ b/static/app/components/search/sources/apiSource.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {withRouter, WithRouterProps} from 'react-router';
import * as Sentry from '@sentry/react';
import debounce from 'lodash/debounce';
@@ -289,7 +289,7 @@ type State = {
searchResults: null | Result[];
};
-class ApiSource extends React.Component<Props, State> {
+class ApiSource extends Component<Props, State> {
static defaultProps = {
searchOptions: {},
};
diff --git a/static/app/components/search/sources/commandSource.tsx b/static/app/components/search/sources/commandSource.tsx
index ab2f87466c906f..d47b6af011dc98 100644
--- a/static/app/components/search/sources/commandSource.tsx
+++ b/static/app/components/search/sources/commandSource.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {PlainRoute} from 'react-router';
import {openHelpSearchModal, openSudo} from 'sentry/actionCreators/modal';
@@ -89,7 +89,7 @@ type State = {
/**
* This source is a hardcoded list of action creators and/or routes maybe
*/
-class CommandSource extends React.Component<Props, State> {
+class CommandSource extends Component<Props, State> {
static defaultProps = {
searchMap: [],
searchOptions: {},
diff --git a/static/app/components/search/sources/formSource.tsx b/static/app/components/search/sources/formSource.tsx
index 1ba9fb990331d0..84bf24e5f6851b 100644
--- a/static/app/components/search/sources/formSource.tsx
+++ b/static/app/components/search/sources/formSource.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {withRouter, WithRouterProps} from 'react-router';
import {loadSearchMap} from 'sentry/actionCreators/formSearch';
@@ -29,7 +29,7 @@ type State = {
fuzzy: null | Fuse<FormSearchField>;
};
-class FormSource extends React.Component<Props, State> {
+class FormSource extends Component<Props, State> {
static defaultProps = {
searchOptions: {},
};
@@ -87,7 +87,7 @@ class FormSource extends React.Component<Props, State> {
type ContainerProps = Omit<Props, 'searchMap'>;
type ContainerState = Pick<Props, 'searchMap'>;
-class FormSourceContainer extends React.Component<ContainerProps, ContainerState> {
+class FormSourceContainer extends Component<ContainerProps, ContainerState> {
state = {
searchMap: FormSearchStore.get(),
};
diff --git a/static/app/components/search/sources/helpSource.tsx b/static/app/components/search/sources/helpSource.tsx
index b6b3c8b6b74b37..84a219a2794889 100644
--- a/static/app/components/search/sources/helpSource.tsx
+++ b/static/app/components/search/sources/helpSource.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {withRouter, WithRouterProps} from 'react-router';
import {
Result as SearchResult,
@@ -41,7 +41,7 @@ const MARK_TAGS = {
highlightPostTag: '</mark>',
};
-class HelpSource extends React.Component<Props, State> {
+class HelpSource extends Component<Props, State> {
state: State = {
loading: false,
results: [],
diff --git a/static/app/components/search/sources/index.tsx b/static/app/components/search/sources/index.tsx
index 0fcabf4d571b8f..2debb63adaede7 100644
--- a/static/app/components/search/sources/index.tsx
+++ b/static/app/components/search/sources/index.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import flatten from 'lodash/flatten';
import type {Fuse} from 'sentry/utils/fuzzySearch';
@@ -24,7 +24,7 @@ type SourceResult = {
results: Result[];
};
-class SearchSources extends React.Component<Props> {
+class SearchSources extends Component<Props> {
// `allSources` will be an array of all result objects from each source
renderResults(allSources: SourceResult[]) {
const {children} = this.props;
diff --git a/static/app/components/search/sources/routeSource.tsx b/static/app/components/search/sources/routeSource.tsx
index 465349ad957487..54a528fd910c5f 100644
--- a/static/app/components/search/sources/routeSource.tsx
+++ b/static/app/components/search/sources/routeSource.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {RouteComponentProps} from 'react-router';
import flattenDepth from 'lodash/flattenDepth';
@@ -72,7 +72,7 @@ type State = {
fuzzy: undefined | null | Fuse<NavigationItem>;
};
-class RouteSource extends React.Component<Props, State> {
+class RouteSource extends Component<Props, State> {
static defaultProps: DefaultProps = {
searchOptions: {},
};
diff --git a/static/app/components/selectMembers/index.tsx b/static/app/components/selectMembers/index.tsx
index cd49757d6c1fe8..5d9b3889a02981 100644
--- a/static/app/components/selectMembers/index.tsx
+++ b/static/app/components/selectMembers/index.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import debounce from 'lodash/debounce';
@@ -55,7 +55,7 @@ type FilterOption<T> = {
/**
* A component that allows you to select either members and/or teams
*/
-class SelectMembers extends React.Component<Props, State> {
+class SelectMembers extends Component<Props, State> {
state: State = {
loading: false,
inputValue: '',
diff --git a/static/app/components/truncate.tsx b/static/app/components/truncate.tsx
index 48a1f1553fd16d..f1505ac755326b 100644
--- a/static/app/components/truncate.tsx
+++ b/static/app/components/truncate.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import space from 'sentry/styles/space';
@@ -21,7 +21,7 @@ type State = {
isExpanded: boolean;
};
-class Truncate extends React.Component<Props, State> {
+class Truncate extends Component<Props, State> {
static defaultProps: DefaultProps = {
className: '',
minLength: 15,
diff --git a/static/app/components/u2f/u2finterface.tsx b/static/app/components/u2f/u2finterface.tsx
index ebe1d5a1c56a6e..7a7143f3cc1022 100644
--- a/static/app/components/u2f/u2finterface.tsx
+++ b/static/app/components/u2f/u2finterface.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import * as Sentry from '@sentry/react';
import * as cbor from 'cbor-web';
@@ -42,7 +42,7 @@ type State = {
responseElement: HTMLInputElement | null;
};
-class U2fInterface extends React.Component<Props, State> {
+class U2fInterface extends Component<Props, State> {
state: State = {
isSupported: null,
formElement: null,
diff --git a/static/app/components/versionHoverCard.tsx b/static/app/components/versionHoverCard.tsx
index 8a49ec43c6164a..15a879215251cf 100644
--- a/static/app/components/versionHoverCard.tsx
+++ b/static/app/components/versionHoverCard.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import {Client} from 'sentry/api';
@@ -42,7 +42,7 @@ type State = {
visible: boolean;
};
-class VersionHoverCard extends React.Component<Props, State> {
+class VersionHoverCard extends Component<Props, State> {
state: State = {
visible: false,
};
diff --git a/static/app/utils/errorHandler.tsx b/static/app/utils/errorHandler.tsx
index 13165d888fbd81..d328696dfea1d6 100644
--- a/static/app/utils/errorHandler.tsx
+++ b/static/app/utils/errorHandler.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import RouteError from 'sentry/views/routeError';
@@ -7,8 +7,8 @@ type State = {
hasError: boolean;
};
-export default function errorHandler<P>(Component: React.ComponentType<P>) {
- class ErrorHandler extends React.Component<P, State> {
+export default function errorHandler<P>(WrappedComponent: React.ComponentType<P>) {
+ class ErrorHandler extends Component<P, State> {
static getDerivedStateFromError(error: Error) {
// Update state so the next render will show the fallback UI.
return {
@@ -37,7 +37,7 @@ export default function errorHandler<P>(Component: React.ComponentType<P>) {
return <RouteError error={this.state.error} />;
}
- return <Component {...this.props} />;
+ return <WrappedComponent {...this.props} />;
}
}
diff --git a/static/app/utils/eventWaiter.tsx b/static/app/utils/eventWaiter.tsx
index e2371694b16723..7ecf291dbf88d2 100644
--- a/static/app/utils/eventWaiter.tsx
+++ b/static/app/utils/eventWaiter.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import * as Sentry from '@sentry/react';
import {Client} from 'sentry/api';
@@ -41,7 +41,7 @@ type EventWaiterState = {
* This is a render prop component that can be used to wait for the first event
* of a project to be received via polling.
*/
-class EventWaiter extends React.Component<EventWaiterProps, EventWaiterState> {
+class EventWaiter extends Component<EventWaiterProps, EventWaiterState> {
state: EventWaiterState = {
firstIssue: null,
};
diff --git a/static/app/utils/metrics/metricsRequest.tsx b/static/app/utils/metrics/metricsRequest.tsx
index 9cecf60216f8a1..7f51b02cdd36fa 100644
--- a/static/app/utils/metrics/metricsRequest.tsx
+++ b/static/app/utils/metrics/metricsRequest.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import isEqual from 'lodash/isEqual';
import omitBy from 'lodash/omitBy';
@@ -71,7 +71,7 @@ type State = {
responsePrevious: MetricsApiResponse | null;
};
-class MetricsRequest extends React.Component<Props, State> {
+class MetricsRequest extends Component<Props, State> {
static defaultProps: DefaultProps = {
includePrevious: false,
includeSeriesData: false,
diff --git a/static/app/utils/performance/histogram/index.tsx b/static/app/utils/performance/histogram/index.tsx
index 12357c7711fcef..d9e832ef3325ed 100644
--- a/static/app/utils/performance/histogram/index.tsx
+++ b/static/app/utils/performance/histogram/index.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {browserHistory} from 'react-router';
import {Location} from 'history';
@@ -22,7 +22,7 @@ type Props = {
zoomKeys: string[];
};
-class Histogram extends React.Component<Props> {
+class Histogram extends Component<Props> {
isZoomed() {
const {location, zoomKeys} = this.props;
return zoomKeys.map(key => location.query[key]).some(value => value !== undefined);
diff --git a/static/app/utils/projects.tsx b/static/app/utils/projects.tsx
index fd72f263f568cb..ac8060866764d6 100644
--- a/static/app/utils/projects.tsx
+++ b/static/app/utils/projects.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import memoize from 'lodash/memoize';
import partition from 'lodash/partition';
import uniqBy from 'lodash/uniqBy';
@@ -119,7 +119,7 @@ type Props = {
slugs?: string[];
} & DefaultProps;
-class BaseProjects extends React.Component<Props, State> {
+class BaseProjects extends Component<Props, State> {
static defaultProps: DefaultProps = {
passthroughPlaceholderProject: true,
};
diff --git a/static/app/views/alerts/incidentRules/triggers/thresholdControl.tsx b/static/app/views/alerts/incidentRules/triggers/thresholdControl.tsx
index 82880e1b8bf181..cf1097a7f837ca 100644
--- a/static/app/views/alerts/incidentRules/triggers/thresholdControl.tsx
+++ b/static/app/views/alerts/incidentRules/triggers/thresholdControl.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import Feature from 'sentry/components/acl/feature';
@@ -31,7 +31,7 @@ type State = {
currentValue: string | null;
};
-class ThresholdControl extends React.Component<Props, State> {
+class ThresholdControl extends Component<Props, State> {
state: State = {
currentValue: null,
};
diff --git a/static/app/views/alerts/issueRuleEditor/memberTeamFields.tsx b/static/app/views/alerts/issueRuleEditor/memberTeamFields.tsx
index 0ad84c84f00329..6ec0855c99cc83 100644
--- a/static/app/views/alerts/issueRuleEditor/memberTeamFields.tsx
+++ b/static/app/views/alerts/issueRuleEditor/memberTeamFields.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import SelectControl from 'sentry/components/forms/selectControl';
@@ -26,7 +26,7 @@ type Props = {
teamValue: string | number;
};
-class MemberTeamFields extends React.Component<Props> {
+class MemberTeamFields extends Component<Props> {
handleChange = (attribute: 'targetType' | 'targetIdentifier', newValue: string) => {
const {onChange, ruleData} = this.props;
if (newValue === ruleData[attribute]) {
diff --git a/static/app/views/dashboardsV2/widgetCard/chart.tsx b/static/app/views/dashboardsV2/widgetCard/chart.tsx
index 0e33087744a16e..8dcb52e4c2493c 100644
--- a/static/app/views/dashboardsV2/widgetCard/chart.tsx
+++ b/static/app/views/dashboardsV2/widgetCard/chart.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {InjectedRouter} from 'react-router';
import {withTheme} from '@emotion/react';
import styled from '@emotion/styled';
@@ -89,7 +89,7 @@ type State = {
containerHeight: number;
};
-class WidgetCardChart extends React.Component<WidgetCardChartProps, State> {
+class WidgetCardChart extends Component<WidgetCardChartProps, State> {
state = {containerHeight: 0};
shouldComponentUpdate(nextProps: WidgetCardChartProps, nextState: State): boolean {
diff --git a/static/app/views/dashboardsV2/widgetCard/index.tsx b/static/app/views/dashboardsV2/widgetCard/index.tsx
index 3d7dd61c8ca8bd..e1b02a8565ae4c 100644
--- a/static/app/views/dashboardsV2/widgetCard/index.tsx
+++ b/static/app/views/dashboardsV2/widgetCard/index.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import LazyLoad from 'react-lazyload';
import {withRouter, WithRouterProps} from 'react-router';
import {useSortable} from '@dnd-kit/sortable';
@@ -70,7 +70,7 @@ type State = {
totalIssuesCount?: string;
};
-class WidgetCard extends React.Component<Props, State> {
+class WidgetCard extends Component<Props, State> {
state: State = {};
renderToolbar() {
const {
diff --git a/static/app/views/dashboardsV2/widgetCard/issueWidgetQueries.tsx b/static/app/views/dashboardsV2/widgetCard/issueWidgetQueries.tsx
index 409f17da6b78e5..53a74c272ccf75 100644
--- a/static/app/views/dashboardsV2/widgetCard/issueWidgetQueries.tsx
+++ b/static/app/views/dashboardsV2/widgetCard/issueWidgetQueries.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import isEqual from 'lodash/isEqual';
import {Client} from 'sentry/api';
@@ -62,7 +62,7 @@ type State = {
totalCount: null | string;
};
-class IssueWidgetQueries extends React.Component<Props, State> {
+class IssueWidgetQueries extends Component<Props, State> {
state: State = {
loading: true,
errorMessage: undefined,
diff --git a/static/app/views/dashboardsV2/widgetCard/releaseWidgetQueries.tsx b/static/app/views/dashboardsV2/widgetCard/releaseWidgetQueries.tsx
index 7e17bf9ac08e4b..f5336eca9f7b62 100644
--- a/static/app/views/dashboardsV2/widgetCard/releaseWidgetQueries.tsx
+++ b/static/app/views/dashboardsV2/widgetCard/releaseWidgetQueries.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import cloneDeep from 'lodash/cloneDeep';
import isEqual from 'lodash/isEqual';
import omit from 'lodash/omit';
@@ -49,7 +49,7 @@ type State = {
timeseriesResults?: Series[];
};
-class ReleaseWidgetQueries extends React.Component<Props, State> {
+class ReleaseWidgetQueries extends Component<Props, State> {
state: State = {
loading: true,
queryFetchID: undefined,
diff --git a/static/app/views/dashboardsV2/widgetCard/widgetQueries.tsx b/static/app/views/dashboardsV2/widgetCard/widgetQueries.tsx
index ce8dfbfeec58b1..3f22d289e2611d 100644
--- a/static/app/views/dashboardsV2/widgetCard/widgetQueries.tsx
+++ b/static/app/views/dashboardsV2/widgetCard/widgetQueries.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import cloneDeep from 'lodash/cloneDeep';
import isEqual from 'lodash/isEqual';
import omit from 'lodash/omit';
@@ -175,7 +175,7 @@ type State = {
timeseriesResults?: Series[];
};
-class WidgetQueries extends React.Component<Props, State> {
+class WidgetQueries extends Component<Props, State> {
state: State = {
loading: true,
queryFetchID: undefined,
diff --git a/static/app/views/eventsV2/miniGraph.tsx b/static/app/views/eventsV2/miniGraph.tsx
index 69480e7f2d51ba..457308da32abc5 100644
--- a/static/app/views/eventsV2/miniGraph.tsx
+++ b/static/app/views/eventsV2/miniGraph.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {withTheme} from '@emotion/react';
import styled from '@emotion/styled';
import {Location} from 'history';
@@ -36,7 +36,7 @@ type Props = {
yAxis?: string[];
};
-class MiniGraph extends React.Component<Props> {
+class MiniGraph extends Component<Props> {
shouldComponentUpdate(nextProps) {
// We pay for the cost of the deep comparison here since it is cheaper
// than the cost for rendering the graph, which can take ~200ms to ~300ms to
@@ -301,8 +301,8 @@ class MiniGraph extends React.Component<Props> {
(Array.isArray(yAxis) && yAxis.length > 1),
};
- const Component = this.getChartComponent(chartType);
- return <Component {...chartOptions} />;
+ const ChartComponent = this.getChartComponent(chartType);
+ return <ChartComponent {...chartOptions} />;
}}
</EventsRequest>
);
diff --git a/static/app/views/eventsV2/results.tsx b/static/app/views/eventsV2/results.tsx
index b434f65adc0ec4..4c58ce3bdb2f39 100644
--- a/static/app/views/eventsV2/results.tsx
+++ b/static/app/views/eventsV2/results.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {browserHistory, InjectedRouter} from 'react-router';
import styled from '@emotion/styled';
import * as Sentry from '@sentry/react';
@@ -89,7 +89,7 @@ function getYAxis(location: Location, eventView: EventView, savedQuery?: SavedQu
: [eventView.getYAxis()];
}
-class Results extends React.Component<Props, State> {
+class Results extends Component<Props, State> {
static getDerivedStateFromProps(nextProps: Readonly<Props>, prevState: State): State {
if (nextProps.savedQuery || !nextProps.loading) {
const eventView = EventView.fromSavedQueryOrLocation(
diff --git a/static/app/views/eventsV2/resultsHeader.tsx b/static/app/views/eventsV2/resultsHeader.tsx
index 707d6c76845671..553a7f4f289dc3 100644
--- a/static/app/views/eventsV2/resultsHeader.tsx
+++ b/static/app/views/eventsV2/resultsHeader.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {InjectedRouter} from 'react-router';
import styled from '@emotion/styled';
import {Location} from 'history';
@@ -36,7 +36,7 @@ type State = {
savedQuery: SavedQuery | undefined;
};
-class ResultsHeader extends React.Component<Props, State> {
+class ResultsHeader extends Component<Props, State> {
state: State = {
savedQuery: undefined,
loading: true,
diff --git a/static/app/views/eventsV2/table/cellAction.tsx b/static/app/views/eventsV2/table/cellAction.tsx
index b4d841d9753e03..0af9a3a90f33e9 100644
--- a/static/app/views/eventsV2/table/cellAction.tsx
+++ b/static/app/views/eventsV2/table/cellAction.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {createPortal} from 'react-dom';
import {Manager, Popper, PopperProps, Reference} from 'react-popper';
import styled from '@emotion/styled';
@@ -287,7 +287,7 @@ type State = {
isOpen: boolean;
};
-class CellAction extends React.Component<Props, State> {
+class CellAction extends Component<Props, State> {
constructor(props: Props) {
super(props);
let portal = document.getElementById('cell-action-portal');
diff --git a/static/app/views/issueList/createSavedSearchModal.tsx b/static/app/views/issueList/createSavedSearchModal.tsx
index 2d55f56bed1a16..f54548ee305cf5 100644
--- a/static/app/views/issueList/createSavedSearchModal.tsx
+++ b/static/app/views/issueList/createSavedSearchModal.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {addLoadingMessage, clearIndicators} from 'sentry/actionCreators/indicator';
import {ModalRenderProps} from 'sentry/actionCreators/modal';
@@ -33,7 +33,7 @@ const DEFAULT_SORT_OPTIONS = [
IssueSortOptions.USER,
];
-class CreateSavedSearchModal extends React.Component<Props, State> {
+class CreateSavedSearchModal extends Component<Props, State> {
state: State = {
isSaving: false,
error: null,
diff --git a/static/app/views/issueList/searchBar.tsx b/static/app/views/issueList/searchBar.tsx
index ee3b70c7c36aa1..5d1b6e7bf426fe 100644
--- a/static/app/views/issueList/searchBar.tsx
+++ b/static/app/views/issueList/searchBar.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {fetchRecentSearches} from 'sentry/actionCreators/savedSearches';
import {Client} from 'sentry/api';
@@ -68,7 +68,7 @@ type State = {
recentSearches: string[];
};
-class IssueListSearchBar extends React.Component<Props, State> {
+class IssueListSearchBar extends Component<Props, State> {
state: State = {
defaultSearchItems: [SEARCH_ITEMS, []],
recentSearches: [],
diff --git a/static/app/views/issueList/tagFilter.tsx b/static/app/views/issueList/tagFilter.tsx
index 83e2225b42bc6d..56125e82554703 100644
--- a/static/app/views/issueList/tagFilter.tsx
+++ b/static/app/views/issueList/tagFilter.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import debounce from 'lodash/debounce';
import {addErrorMessage} from 'sentry/actionCreators/indicator';
@@ -31,7 +31,7 @@ type State = {
options?: SelectOption[];
};
-class IssueListTagFilter extends React.Component<Props, State> {
+class IssueListTagFilter extends Component<Props, State> {
static defaultProps = defaultProps;
state: State = {
diff --git a/static/app/views/onboarding/components/fallingError.tsx b/static/app/views/onboarding/components/fallingError.tsx
index 3434723bd85bd7..046a679408bafa 100644
--- a/static/app/views/onboarding/components/fallingError.tsx
+++ b/static/app/views/onboarding/components/fallingError.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {motion} from 'framer-motion';
import testableTransition from 'sentry/utils/testableTransition';
@@ -20,7 +20,7 @@ type State = {
isFalling: boolean;
};
-class FallingError extends React.Component<Props, State> {
+class FallingError extends Component<Props, State> {
state: State = {
isFalling: false,
fallCount: 0,
diff --git a/static/app/views/onboarding/createSampleEventButton.tsx b/static/app/views/onboarding/createSampleEventButton.tsx
index 800aad6abd647f..d0891e9b6a2074 100644
--- a/static/app/views/onboarding/createSampleEventButton.tsx
+++ b/static/app/views/onboarding/createSampleEventButton.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {browserHistory} from 'react-router';
import * as Sentry from '@sentry/react';
@@ -53,10 +53,7 @@ async function latestEventAvailable(
}
}
-class CreateSampleEventButton extends React.Component<
- CreateSampleEventButtonProps,
- State
-> {
+class CreateSampleEventButton extends Component<CreateSampleEventButtonProps, State> {
state: State = {
creating: false,
};
diff --git a/static/app/views/organizationGroupDetails/groupEvents.tsx b/static/app/views/organizationGroupDetails/groupEvents.tsx
index 691911268feee3..c3a915030be6c4 100644
--- a/static/app/views/organizationGroupDetails/groupEvents.tsx
+++ b/static/app/views/organizationGroupDetails/groupEvents.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {browserHistory, RouteComponentProps} from 'react-router';
import styled from '@emotion/styled';
import pick from 'lodash/pick';
@@ -35,7 +35,7 @@ type State = {
query: string;
};
-class GroupEvents extends React.Component<Props, State> {
+class GroupEvents extends Component<Props, State> {
constructor(props: Props) {
super(props);
diff --git a/static/app/views/organizationGroupDetails/groupMerged/mergedItem.tsx b/static/app/views/organizationGroupDetails/groupMerged/mergedItem.tsx
index fff81066e4145d..4acc6b38b18934 100644
--- a/static/app/views/organizationGroupDetails/groupMerged/mergedItem.tsx
+++ b/static/app/views/organizationGroupDetails/groupMerged/mergedItem.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import GroupingActions from 'sentry/actions/groupingActions';
@@ -21,7 +21,7 @@ type State = {
collapsed: boolean;
};
-class MergedItem extends React.Component<Props, State> {
+class MergedItem extends Component<Props, State> {
state: State = {
collapsed: false,
checked: false,
diff --git a/static/app/views/organizationGroupDetails/groupMerged/mergedToolbar.tsx b/static/app/views/organizationGroupDetails/groupMerged/mergedToolbar.tsx
index 124e2b69d361b6..7b973e07e9d800 100644
--- a/static/app/views/organizationGroupDetails/groupMerged/mergedToolbar.tsx
+++ b/static/app/views/organizationGroupDetails/groupMerged/mergedToolbar.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import pick from 'lodash/pick';
@@ -26,7 +26,7 @@ type State = {
unmergeList: Map<any, any>;
};
-class MergedToolbar extends React.Component<Props, State> {
+class MergedToolbar extends Component<Props, State> {
state: State = this.getInitialState();
getInitialState() {
diff --git a/static/app/views/organizationGroupDetails/groupSimilarIssues/similarStackTrace/index.tsx b/static/app/views/organizationGroupDetails/groupSimilarIssues/similarStackTrace/index.tsx
index a48b275058a6cf..0cb2487ad6eb3e 100644
--- a/static/app/views/organizationGroupDetails/groupSimilarIssues/similarStackTrace/index.tsx
+++ b/static/app/views/organizationGroupDetails/groupSimilarIssues/similarStackTrace/index.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {browserHistory, RouteComponentProps} from 'react-router';
import styled from '@emotion/styled';
import {Location} from 'history';
@@ -41,7 +41,7 @@ type State = {
v2: boolean;
};
-class SimilarStackTrace extends React.Component<Props, State> {
+class SimilarStackTrace extends Component<Props, State> {
state: State = {
similarItems: [],
filteredSimilarItems: [],
diff --git a/static/app/views/organizationGroupDetails/groupSimilarIssues/similarStackTrace/item.tsx b/static/app/views/organizationGroupDetails/groupSimilarIssues/similarStackTrace/item.tsx
index e7a739c7c1ddae..0be0dc6ae6ec04 100644
--- a/static/app/views/organizationGroupDetails/groupSimilarIssues/similarStackTrace/item.tsx
+++ b/static/app/views/organizationGroupDetails/groupSimilarIssues/similarStackTrace/item.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {css} from '@emotion/react';
import styled from '@emotion/styled';
import classNames from 'classnames';
@@ -42,7 +42,7 @@ const initialState = {visible: true, checked: false, busy: false};
type State = typeof initialState;
-class Item extends React.Component<Props, State> {
+class Item extends Component<Props, State> {
state: State = initialState;
componentWillUnmount() {
diff --git a/static/app/views/organizationIntegrations/addIntegration.tsx b/static/app/views/organizationIntegrations/addIntegration.tsx
index f89ae51a5d0954..e04896261dbc2e 100644
--- a/static/app/views/organizationIntegrations/addIntegration.tsx
+++ b/static/app/views/organizationIntegrations/addIntegration.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import * as qs from 'query-string';
import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
@@ -25,7 +25,7 @@ type Props = {
modalParams?: {[key: string]: string};
};
-export default class AddIntegration extends React.Component<Props> {
+export default class AddIntegration extends Component<Props> {
componentDidMount() {
window.addEventListener('message', this.didReceiveMessage);
}
diff --git a/static/app/views/organizationIntegrations/addIntegrationButton.tsx b/static/app/views/organizationIntegrations/addIntegrationButton.tsx
index db8a073ecb16e2..90a6749a184ae0 100644
--- a/static/app/views/organizationIntegrations/addIntegrationButton.tsx
+++ b/static/app/views/organizationIntegrations/addIntegrationButton.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import Button, {ButtonPropsWithoutAriaLabel} from 'sentry/components/button';
import Tooltip from 'sentry/components/tooltip';
@@ -18,7 +18,7 @@ interface AddIntegrationButtonProps
reinstall?: boolean;
}
-export default class AddIntegrationButton extends React.Component<AddIntegrationButtonProps> {
+export default class AddIntegrationButton extends Component<AddIntegrationButtonProps> {
render() {
const {
provider,
diff --git a/static/app/views/organizationStats/usageTable/index.tsx b/static/app/views/organizationStats/usageTable/index.tsx
index 6b325dec621475..7564d45169e294 100644
--- a/static/app/views/organizationStats/usageTable/index.tsx
+++ b/static/app/views/organizationStats/usageTable/index.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import ErrorPanel from 'sentry/components/charts/errorPanel';
@@ -40,7 +40,7 @@ export type TableStat = {
total: number;
};
-class UsageTable extends React.Component<Props> {
+class UsageTable extends Component<Props> {
get formatUsageOptions() {
const {dataCategory} = this.props;
diff --git a/static/app/views/projectDetail/charts/projectSessionsChartRequest.tsx b/static/app/views/projectDetail/charts/projectSessionsChartRequest.tsx
index a57c549ae753ec..34667220acc53c 100644
--- a/static/app/views/projectDetail/charts/projectSessionsChartRequest.tsx
+++ b/static/app/views/projectDetail/charts/projectSessionsChartRequest.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {withTheme} from '@emotion/react';
import isEqual from 'lodash/isEqual';
import omit from 'lodash/omit';
@@ -65,7 +65,7 @@ type State = {
totalSessions: number | null;
};
-class ProjectSessionsChartRequest extends React.Component<Props, State> {
+class ProjectSessionsChartRequest extends Component<Props, State> {
state: State = {
reloading: false,
errored: false,
diff --git a/static/app/views/projects/redirectDeprecatedProjectRoute.tsx b/static/app/views/projects/redirectDeprecatedProjectRoute.tsx
index 21daccc761ff80..246544236df0ef 100644
--- a/static/app/views/projects/redirectDeprecatedProjectRoute.tsx
+++ b/static/app/views/projects/redirectDeprecatedProjectRoute.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {RouteComponentProps} from 'react-router';
import styled from '@emotion/styled';
import isString from 'lodash/isString';
@@ -34,7 +34,7 @@ type ChildProps = DetailsState & {
projectId: null | string;
};
-class ProjectDetailsInner extends React.Component<DetailsProps, DetailsState> {
+class ProjectDetailsInner extends Component<DetailsProps, DetailsState> {
state: DetailsState = {
loading: true,
error: null,
diff --git a/static/app/views/releases/detail/commitsAndFiles/withReleaseRepos.tsx b/static/app/views/releases/detail/commitsAndFiles/withReleaseRepos.tsx
index ed7fed6c590218..c10271b25421ca 100644
--- a/static/app/views/releases/detail/commitsAndFiles/withReleaseRepos.tsx
+++ b/static/app/views/releases/detail/commitsAndFiles/withReleaseRepos.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {RouteComponentProps} from 'react-router';
import * as Sentry from '@sentry/react';
@@ -39,7 +39,7 @@ type State = {
function withReleaseRepos<P extends DependentProps>(
WrappedComponent: React.ComponentType<P>
) {
- class WithReleaseRepos extends React.Component<P & HoCsProps, State> {
+ class WithReleaseRepos extends Component<P & HoCsProps, State> {
static displayName = `withReleaseRepos(${getDisplayName(WrappedComponent)})`;
state: State = {
diff --git a/static/app/views/releases/detail/overview/releaseComparisonChart/releaseSessionsChart.tsx b/static/app/views/releases/detail/overview/releaseComparisonChart/releaseSessionsChart.tsx
index a9cae2903c13a2..42664d07250a5a 100644
--- a/static/app/views/releases/detail/overview/releaseComparisonChart/releaseSessionsChart.tsx
+++ b/static/app/views/releases/detail/overview/releaseComparisonChart/releaseSessionsChart.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {withRouter, WithRouterProps} from 'react-router';
import {withTheme} from '@emotion/react';
import round from 'lodash/round';
@@ -58,7 +58,7 @@ type Props = {
utc?: boolean;
} & WithRouterProps;
-class ReleaseSessionsChart extends React.Component<Props> {
+class ReleaseSessionsChart extends Component<Props> {
formatTooltipValue = (value: string | number | null, label?: string) => {
if (label && Object.values(releaseMarkLinesLabels).includes(label)) {
return '';
diff --git a/static/app/views/releases/list/releasesRequest.tsx b/static/app/views/releases/list/releasesRequest.tsx
index c8316025760525..01ddf2da78c13b 100644
--- a/static/app/views/releases/list/releasesRequest.tsx
+++ b/static/app/views/releases/list/releasesRequest.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {Location} from 'history';
import isEqual from 'lodash/isEqual';
import omit from 'lodash/omit';
@@ -111,7 +111,7 @@ type State = {
totalCountByReleaseInPeriod: SessionApiResponse | null;
};
-class ReleasesRequest extends React.Component<Props, State> {
+class ReleasesRequest extends Component<Props, State> {
state: State = {
loading: false,
errored: false,
diff --git a/static/app/views/settings/account/accountSettingsLayout.tsx b/static/app/views/settings/account/accountSettingsLayout.tsx
index 7ad0fb08b75050..3f90cfa3d342aa 100644
--- a/static/app/views/settings/account/accountSettingsLayout.tsx
+++ b/static/app/views/settings/account/accountSettingsLayout.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {fetchOrganizationDetails} from 'sentry/actionCreators/organizations';
import SentryTypes from 'sentry/sentryTypes';
@@ -11,7 +11,7 @@ type Props = React.ComponentProps<typeof SettingsLayout> & {
organization: Organization;
};
-class AccountSettingsLayout extends React.Component<Props> {
+class AccountSettingsLayout extends Component<Props> {
static childContextTypes = {
organization: SentryTypes.Organization,
};
diff --git a/static/app/views/settings/components/dataScrubbing/index.tsx b/static/app/views/settings/components/dataScrubbing/index.tsx
index f049c4e804e068..382fe63c7fe9d4 100644
--- a/static/app/views/settings/components/dataScrubbing/index.tsx
+++ b/static/app/views/settings/components/dataScrubbing/index.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
@@ -39,10 +39,7 @@ type State = {
relayPiiConfig?: string;
};
-class DataScrubbing<T extends ProjectId = undefined> extends React.Component<
- Props<T>,
- State
-> {
+class DataScrubbing<T extends ProjectId = undefined> extends Component<Props<T>, State> {
state: State = {
rules: [],
savedRules: [],
diff --git a/static/app/views/settings/components/dataScrubbing/modals/form/eventIdField.tsx b/static/app/views/settings/components/dataScrubbing/modals/form/eventIdField.tsx
index 83f6f42c84bfbf..a35a22384497ce 100644
--- a/static/app/views/settings/components/dataScrubbing/modals/form/eventIdField.tsx
+++ b/static/app/views/settings/components/dataScrubbing/modals/form/eventIdField.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import isEqual from 'lodash/isEqual';
@@ -23,7 +23,7 @@ type State = {
value: string;
};
-class EventIdField extends React.Component<Props, State> {
+class EventIdField extends Component<Props, State> {
state: State = {...this.props.eventId};
componentDidUpdate(prevProps: Props) {
diff --git a/static/app/views/settings/components/dataScrubbing/modals/modalManager.tsx b/static/app/views/settings/components/dataScrubbing/modals/modalManager.tsx
index 814b3995a90ef7..5962bef69b081b 100644
--- a/static/app/views/settings/components/dataScrubbing/modals/modalManager.tsx
+++ b/static/app/views/settings/components/dataScrubbing/modals/modalManager.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import isEqual from 'lodash/isEqual';
import omit from 'lodash/omit';
@@ -50,7 +50,7 @@ type State = {
values: Values;
};
-class ModalManager<T extends ProjectId> extends React.Component<Props<T>, State> {
+class ModalManager<T extends ProjectId> extends Component<Props<T>, State> {
state = this.getDefaultState();
componentDidMount() {
diff --git a/static/app/views/settings/components/settingsBreadcrumb/breadcrumbDropdown.tsx b/static/app/views/settings/components/settingsBreadcrumb/breadcrumbDropdown.tsx
index b1225caf93fa3e..81ee1eaff37045 100644
--- a/static/app/views/settings/components/settingsBreadcrumb/breadcrumbDropdown.tsx
+++ b/static/app/views/settings/components/settingsBreadcrumb/breadcrumbDropdown.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import DropdownAutoCompleteMenu from 'sentry/components/dropdownAutoComplete/menu';
import {Item} from 'sentry/components/dropdownAutoComplete/types';
@@ -29,7 +29,7 @@ type State = {
isOpen: boolean;
};
-class BreadcrumbDropdown extends React.Component<BreadcrumbDropdownProps, State> {
+class BreadcrumbDropdown extends Component<BreadcrumbDropdownProps, State> {
state: State = {
isOpen: false,
};
diff --git a/static/app/views/settings/organization/organizationSettingsNavigation.tsx b/static/app/views/settings/organization/organizationSettingsNavigation.tsx
index 6228f8011b5e64..1b36d6bec89bf6 100644
--- a/static/app/views/settings/organization/organizationSettingsNavigation.tsx
+++ b/static/app/views/settings/organization/organizationSettingsNavigation.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import HookStore from 'sentry/stores/hookStore';
import {Organization} from 'sentry/types';
@@ -17,7 +17,7 @@ type State = {
hooks: React.ReactElement[];
};
-class OrganizationSettingsNavigation extends React.Component<Props, State> {
+class OrganizationSettingsNavigation extends Component<Props, State> {
state: State = this.getHooks();
componentDidMount() {
diff --git a/static/app/views/settings/organizationRelay/modals/modalManager.tsx b/static/app/views/settings/organizationRelay/modals/modalManager.tsx
index ff84646bb81ee1..ea0f2ff7080303 100644
--- a/static/app/views/settings/organizationRelay/modals/modalManager.tsx
+++ b/static/app/views/settings/organizationRelay/modals/modalManager.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import isEqual from 'lodash/isEqual';
import omit from 'lodash/omit';
@@ -31,10 +31,10 @@ type State = {
values: Values;
};
-class DialogManager<
- P extends Props = Props,
- S extends State = State
-> extends React.Component<P, S> {
+class DialogManager<P extends Props = Props, S extends State = State> extends Component<
+ P,
+ S
+> {
state = this.getDefaultState();
componentDidMount() {
diff --git a/static/app/views/settings/organizationTeams/allTeamsRow.tsx b/static/app/views/settings/organizationTeams/allTeamsRow.tsx
index eef504f5e8ceb9..8a548bec8f9862 100644
--- a/static/app/views/settings/organizationTeams/allTeamsRow.tsx
+++ b/static/app/views/settings/organizationTeams/allTeamsRow.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
@@ -27,7 +27,7 @@ type State = {
loading: boolean;
};
-class AllTeamsRow extends React.Component<Props, State> {
+class AllTeamsRow extends Component<Props, State> {
state: State = {
loading: false,
error: false,
diff --git a/static/app/views/settings/organizationTeams/organizationAccessRequests.tsx b/static/app/views/settings/organizationTeams/organizationAccessRequests.tsx
index db127c899b1dc2..99973921b5b7a9 100644
--- a/static/app/views/settings/organizationTeams/organizationAccessRequests.tsx
+++ b/static/app/views/settings/organizationTeams/organizationAccessRequests.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import styled from '@emotion/styled';
import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
@@ -28,7 +28,7 @@ type HandleOpts = {
successMessage: string;
};
-class OrganizationAccessRequests extends React.Component<Props, State> {
+class OrganizationAccessRequests extends Component<Props, State> {
state: State = {
accessRequestBusy: {},
};
diff --git a/static/app/views/settings/organizationTeams/teamMembers.tsx b/static/app/views/settings/organizationTeams/teamMembers.tsx
index a944c10b159481..81baa5b3bce034 100644
--- a/static/app/views/settings/organizationTeams/teamMembers.tsx
+++ b/static/app/views/settings/organizationTeams/teamMembers.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {RouteComponentProps} from 'react-router';
import styled from '@emotion/styled';
import debounce from 'lodash/debounce';
@@ -49,7 +49,7 @@ type State = {
teamMemberList: Member[];
};
-class TeamMembers extends React.Component<Props, State> {
+class TeamMembers extends Component<Props, State> {
state: State = {
loading: true,
error: false,
diff --git a/static/app/views/settings/settingsIndex.tsx b/static/app/views/settings/settingsIndex.tsx
index 2bca1a24ab280a..c36cb7649ae3b9 100644
--- a/static/app/views/settings/settingsIndex.tsx
+++ b/static/app/views/settings/settingsIndex.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Component} from 'react';
import {RouteComponentProps} from 'react-router';
import {css} from '@emotion/react';
import styled from '@emotion/styled';
@@ -45,7 +45,7 @@ interface SettingsIndexProps extends RouteComponentProps<{}, {}> {
organization: Organization;
}
-class SettingsIndex extends React.Component<SettingsIndexProps> {
+class SettingsIndex extends Component<SettingsIndexProps> {
componentDidUpdate(prevProps: SettingsIndexProps) {
const {organization} = this.props;
if (prevProps.organization === organization) {
|
10131be1ce7f70a31a067c40720589b13af8ad50
|
2024-09-16 19:32:05
|
Ash
|
feat(insights): Tokenize and format MongoDB queries in the table (#77425)
| false
|
Tokenize and format MongoDB queries in the table (#77425)
|
feat
|
diff --git a/static/app/views/insights/common/components/tableCells/spanDescriptionCell.tsx b/static/app/views/insights/common/components/tableCells/spanDescriptionCell.tsx
index d5ab767a0122df..d192a89675f633 100644
--- a/static/app/views/insights/common/components/tableCells/spanDescriptionCell.tsx
+++ b/static/app/views/insights/common/components/tableCells/spanDescriptionCell.tsx
@@ -7,6 +7,8 @@ import {space} from 'sentry/styles/space';
import {SQLishFormatter} from 'sentry/utils/sqlish/SQLishFormatter';
import {FullSpanDescription} from 'sentry/views/insights/common/components/fullSpanDescription';
import {SpanGroupDetailsLink} from 'sentry/views/insights/common/components/spanGroupDetailsLink';
+import {SupportedDatabaseSystem} from 'sentry/views/insights/database/utils/constants';
+import {formatMongoDBQuery} from 'sentry/views/insights/database/utils/formatMongoDBQuery';
import {ModuleName, SpanMetricsField} from 'sentry/views/insights/types';
const formatter = new SQLishFormatter();
@@ -17,9 +19,11 @@ interface Props {
description: string;
moduleName: ModuleName.DB | ModuleName.RESOURCE;
projectId: number;
- extraLinkQueryParams?: Record<string, string>; // extra query params to add to the link
+ extraLinkQueryParams?: Record<string, string>;
group?: string;
+ spanAction?: string;
spanOp?: string;
+ system?: string;
}
export function SpanDescriptionCell({
@@ -28,6 +32,8 @@ export function SpanDescriptionCell({
moduleName,
spanOp,
projectId,
+ system,
+ spanAction,
extraLinkQueryParams,
}: Props) {
const formatterDescription = useMemo(() => {
@@ -35,8 +41,12 @@ export function SpanDescriptionCell({
return rawDescription;
}
+ if (system === SupportedDatabaseSystem.MONGODB) {
+ return spanAction ? formatMongoDBQuery(rawDescription, spanAction) : rawDescription;
+ }
+
return formatter.toSimpleMarkup(rawDescription);
- }, [moduleName, rawDescription]);
+ }, [moduleName, rawDescription, spanAction, system]);
if (!rawDescription) {
return NULL_DESCRIPTION;
diff --git a/static/app/views/insights/database/components/databasePageFilters.tsx b/static/app/views/insights/database/components/databasePageFilters.tsx
index c00a51fe1768fc..cc5c74e8e488c8 100644
--- a/static/app/views/insights/database/components/databasePageFilters.tsx
+++ b/static/app/views/insights/database/components/databasePageFilters.tsx
@@ -9,7 +9,7 @@ import {ModulePageFilterBar} from 'sentry/views/insights/common/components/modul
import {ActionSelector} from 'sentry/views/insights/common/views/spans/selectors/actionSelector';
import {DomainSelector} from 'sentry/views/insights/common/views/spans/selectors/domainSelector';
import {DatabaseSystemSelector} from 'sentry/views/insights/database/components/databaseSystemSelector';
-import {SupportedDatabaseSystems} from 'sentry/views/insights/database/utils/constants';
+import {SupportedDatabaseSystem} from 'sentry/views/insights/database/utils/constants';
import {ModuleName} from 'sentry/views/insights/types';
type Props = {
@@ -41,7 +41,7 @@ export function DatabasePageFilters(props: Props) {
moduleName={ModuleName.DB}
value={table ?? ''}
domainAlias={
- system === SupportedDatabaseSystems.MONGODB ? t('Collection') : t('Table')
+ system === SupportedDatabaseSystem.MONGODB ? t('Collection') : t('Table')
}
additionalQuery={additionalQuery}
/>
diff --git a/static/app/views/insights/database/components/tables/queriesTable.tsx b/static/app/views/insights/database/components/tables/queriesTable.tsx
index 41cb95993fcde8..28c5b5c15604e6 100644
--- a/static/app/views/insights/database/components/tables/queriesTable.tsx
+++ b/static/app/views/insights/database/components/tables/queriesTable.tsx
@@ -27,6 +27,7 @@ type Row = Pick<
| 'project.id'
| 'span.description'
| 'span.group'
+ | 'span.action'
| 'spm()'
| 'avg(span.self_time)'
| 'sum(span.self_time)'
@@ -79,9 +80,10 @@ interface Props {
pageLinks?: string;
};
sort: ValidSort;
+ system: string;
}
-export function QueriesTable({response, sort}: Props) {
+export function QueriesTable({response, sort, system}: Props) {
const {data, isLoading, meta, pageLinks} = response;
const location = useLocation();
const organization = useOrganization();
@@ -119,7 +121,7 @@ export function QueriesTable({response, sort}: Props) {
sortParameterName: QueryParameterNames.SPANS_SORT,
}),
renderBodyCell: (column, row) =>
- renderBodyCell(column, row, meta, location, organization),
+ renderBodyCell(column, row, meta, location, organization, system),
}}
/>
<Pagination
@@ -142,7 +144,8 @@ function renderBodyCell(
row: Row,
meta: EventsMetaType | undefined,
location: Location,
- organization: Organization
+ organization: Organization,
+ system: string
) {
if (column.key === 'span.description') {
return (
@@ -151,6 +154,8 @@ function renderBodyCell(
description={row['span.description']}
group={row['span.group']}
projectId={row['project.id']}
+ system={system}
+ spanAction={row['span.action']}
/>
);
}
diff --git a/static/app/views/insights/database/utils/constants.tsx b/static/app/views/insights/database/utils/constants.tsx
index db48b7afc0c2f0..72b0f6340f0f09 100644
--- a/static/app/views/insights/database/utils/constants.tsx
+++ b/static/app/views/insights/database/utils/constants.tsx
@@ -4,7 +4,7 @@
*
* https://github.com/getsentry/sentry-python/blob/master/sentry_sdk/integrations/sqlalchemy.py#L125
*/
-export enum SupportedDatabaseSystems {
+export enum SupportedDatabaseSystem {
// SQL
SQLITE = 'sqlite',
POSTGRESQL = 'postgresql',
@@ -15,11 +15,11 @@ export enum SupportedDatabaseSystems {
MONGODB = 'mongodb',
}
-export const DATABASE_SYSTEM_TO_LABEL: Record<SupportedDatabaseSystems, string> = {
- [SupportedDatabaseSystems.SQLITE]: 'SQLite',
- [SupportedDatabaseSystems.POSTGRESQL]: 'PostgreSQL',
- [SupportedDatabaseSystems.MARIADB]: 'MariaDB',
- [SupportedDatabaseSystems.MYSQL]: 'MySQL',
- [SupportedDatabaseSystems.ORACLE]: 'Oracle',
- [SupportedDatabaseSystems.MONGODB]: 'MongoDB',
+export const DATABASE_SYSTEM_TO_LABEL: Record<SupportedDatabaseSystem, string> = {
+ [SupportedDatabaseSystem.SQLITE]: 'SQLite',
+ [SupportedDatabaseSystem.POSTGRESQL]: 'PostgreSQL',
+ [SupportedDatabaseSystem.MARIADB]: 'MariaDB',
+ [SupportedDatabaseSystem.MYSQL]: 'MySQL',
+ [SupportedDatabaseSystem.ORACLE]: 'Oracle',
+ [SupportedDatabaseSystem.MONGODB]: 'MongoDB',
};
diff --git a/static/app/views/insights/database/utils/formatMongoDBQuery.spec.tsx b/static/app/views/insights/database/utils/formatMongoDBQuery.spec.tsx
new file mode 100644
index 00000000000000..c08bbf659b980b
--- /dev/null
+++ b/static/app/views/insights/database/utils/formatMongoDBQuery.spec.tsx
@@ -0,0 +1,95 @@
+import {Fragment} from 'react';
+
+import {render, screen} from 'sentry-test/reactTestingLibrary';
+
+import {formatMongoDBQuery} from 'sentry/views/insights/database/utils/formatMongoDBQuery';
+
+describe('formatMongoDBQuery', function () {
+ it('correctly formats MongoDB JSON strings and can handle all primitive types', function () {
+ const query =
+ '{"stringKey":"test","insert":"my_collection","numericKey":7,"booleanKey":true,"nullKey":null}';
+
+ const tokenizedQuery = formatMongoDBQuery(query, 'insert');
+ render(<Fragment>{tokenizedQuery}</Fragment>);
+
+ const boldedText = screen.getByText(/"insert": "my_collection"/i);
+ expect(boldedText).toBeInTheDocument();
+ // It should be bolded and correctly spaced
+ expect(boldedText).toContainHTML('<b>"insert": "my_collection"</b>');
+
+ // Get the other tokens and confirm they are not bolded
+ const stringToken = screen.getByText(/"stringkey": "test"/i);
+ const numericToken = screen.getByText(/"numerickey": 7/i);
+ const booleanToken = screen.getByText(/"booleankey": true/i);
+ const nullToken = screen.getByText(/"nullkey": null/i);
+
+ expect(stringToken).toContainHTML('<span>"stringKey": "test"</span>');
+ expect(numericToken).toContainHTML('<span>"numericKey": 7</span>');
+ expect(booleanToken).toContainHTML('<span>"booleanKey": true</span>');
+ expect(nullToken).toContainHTML('<span>"nullKey": null</span>');
+ });
+
+ it('correctly formats MongoDB JSON strings that includes nested objects', function () {
+ const query =
+ '{"objectKey":{"nestedObject":{"deeplyNested":{}}},"somethingElse":100,"find":"my_collection"}';
+
+ const tokenizedQuery = formatMongoDBQuery(query, 'find');
+ render(<Fragment>{tokenizedQuery}</Fragment>);
+
+ const boldedText = screen.getByText(/"find": "my_collection"/i);
+ expect(boldedText).toBeInTheDocument();
+ // It should be bolded and correctly spaced
+ expect(boldedText).toContainHTML('<b>"find": "my_collection"</b>');
+
+ const objToken = screen.getByText(/"objectkey": \{/i);
+
+ expect(objToken).toContainHTML(
+ '<span>"objectKey": { "nestedObject": { "deeplyNested": {} } }</span>'
+ );
+ });
+
+ it('correctly formats MongoDB JSON strings that include arrays', function () {
+ const query =
+ '{"arrayKey":[1,2,{"objInArray":{"objInObjInArray":{}}},3,4],"somethingElse":100,"delete":"my_collection"}';
+
+ const tokenizedQuery = formatMongoDBQuery(query, 'delete');
+ render(<Fragment>{tokenizedQuery}</Fragment>);
+
+ const boldedText = screen.getByText(/"delete": "my_collection"/i);
+ expect(boldedText).toBeInTheDocument();
+ // It should be bolded and correctly spaced
+ expect(boldedText).toContainHTML('<b>"delete": "my_collection"</b>');
+
+ const arrayToken = screen.getByText(/"arraykey": \[/i);
+ expect(arrayToken).toContainHTML(
+ '<span>"arrayKey": [1, 2, { "objInArray": { "objInObjInArray": {} } }, 3, 4]</span>'
+ );
+ });
+
+ it('correctly formats MongoDB JSON strings that include nested arrays', function () {
+ const query =
+ '{"deeplyNestedArrayWithObjects":[1,2,3,[1,2,[null,true,[{},{},{"test":[[1,2],[3,4]]},{}]]],4],"findOneAndDelete":"my_collection"}';
+
+ const tokenizedQuery = formatMongoDBQuery(query, 'findOneAndDelete');
+ render(<Fragment>{tokenizedQuery}</Fragment>);
+
+ const boldedText = screen.getByText(/"findOneAndDelete": "my_collection"/i);
+ expect(boldedText).toBeInTheDocument();
+ // It should be bolded and correctly spaced
+ expect(boldedText).toContainHTML('<b>"findOneAndDelete": "my_collection"</b>');
+
+ const clusterFudgeToken = screen.getByText(
+ /"deeplynestedarraywithobjects": \[1, 2, 3, \[1, 2, \[null, true, \[\{\}, \{\}, \{ "test": \[\[1, 2\], \[3, 4\]\] \}, \{\}\]\]\], 4\]/i
+ );
+
+ expect(clusterFudgeToken).toContainHTML(
+ '<span>"deeplyNestedArrayWithObjects": [1, 2, 3, [1, 2, [null, true, [{}, {}, { "test": [[1, 2], [3, 4]] }, {}]]], 4]</span>'
+ );
+ });
+
+ it('returns an unformatted string when given invalid JSON', function () {
+ const query = "{'foo': 'bar'}";
+ const tokenizedQuery = formatMongoDBQuery(query, 'find');
+ expect(tokenizedQuery).toEqual(query);
+ });
+});
diff --git a/static/app/views/insights/database/utils/formatMongoDBQuery.tsx b/static/app/views/insights/database/utils/formatMongoDBQuery.tsx
new file mode 100644
index 00000000000000..d5b728f46464ef
--- /dev/null
+++ b/static/app/views/insights/database/utils/formatMongoDBQuery.tsx
@@ -0,0 +1,141 @@
+import type {ReactElement} from 'react';
+import * as Sentry from '@sentry/react';
+
+type JSONValue = string | number | object | boolean | null;
+
+/**
+ * Takes in a MongoDB query JSON string and outputs it as HTML tokens.
+ * Performs some processing to surface the DB operation and collection so they are the first key-value
+ * pair in the query, and **bolds** the operation
+ *
+ * @param query The query as a JSON string
+ * @param command The DB command, e.g. `find`. This is available as a tag on database spans
+ */
+export function formatMongoDBQuery(query: string, command: string) {
+ const sentrySpan = Sentry.startInactiveSpan({
+ op: 'function',
+ name: 'formatMongoDBQuery',
+ attributes: {
+ query,
+ command,
+ },
+ onlyIfParent: true,
+ });
+
+ let queryObject: Record<string, JSONValue> = {};
+ try {
+ queryObject = JSON.parse(query);
+ } catch {
+ return query;
+ }
+
+ const tokens: ReactElement[] = [];
+ const tempTokens: ReactElement[] = [];
+
+ const queryEntries = Object.entries(queryObject);
+ queryEntries.forEach(([key, val], index) => {
+ // Push the bolded entry into tokens so it is the first entry displayed.
+ // The other tokens will be pushed into tempTokens, and then copied into tokens afterwards
+ const isBoldedEntry = key.toLowerCase() === command.toLowerCase();
+
+ if (index === queryEntries.length - 1) {
+ isBoldedEntry
+ ? tokens.push(jsonEntryToToken(key, val, true))
+ : tempTokens.push(jsonEntryToToken(key, val));
+
+ return;
+ }
+
+ if (isBoldedEntry) {
+ tokens.push(jsonEntryToToken(key, val, true));
+ tokens.push(stringToToken(', ', `${key}:${val},`));
+ return;
+ }
+
+ tempTokens.push(jsonEntryToToken(key, val));
+ tempTokens.push(stringToToken(', ', `${key}:${val},`));
+ });
+
+ tempTokens.forEach(token => tokens.push(token));
+
+ sentrySpan.end();
+
+ return tokens;
+}
+
+function jsonEntryToToken(key: string, value: JSONValue, isBold?: boolean) {
+ const tokenString = jsonToTokenizedString(value, key);
+ return stringToToken(tokenString, `${key}:${value}`, isBold);
+}
+
+function jsonToTokenizedString(value: JSONValue | JSONValue[], key?: string): string {
+ let result = '';
+ if (key) {
+ result = `"${key}": `;
+ }
+
+ // Case 1: Value is null
+ if (!value) {
+ result += 'null';
+ return result;
+ }
+
+ // Case 2: Value is a string
+ if (typeof value === 'string') {
+ result += `"${value}"`;
+ return result;
+ }
+
+ // Case 3: Value is one of the other primitive types
+ if (typeof value === 'number' || typeof value === 'boolean') {
+ result += `${value}`;
+ return result;
+ }
+
+ // Case 4: Value is an array
+ if (Array.isArray(value)) {
+ result += '[';
+
+ value.forEach((item, index) => {
+ if (index === value.length - 1) {
+ result += jsonToTokenizedString(item);
+ } else {
+ result += `${jsonToTokenizedString(item)}, `;
+ }
+ });
+
+ result += ']';
+
+ return result;
+ }
+
+ // Case 5: Value is an object
+ if (typeof value === 'object') {
+ const entries = Object.entries(value);
+
+ if (entries.length === 0) {
+ result += '{}';
+ return result;
+ }
+
+ result += '{ ';
+
+ entries.forEach(([_key, val], index) => {
+ if (index === entries.length - 1) {
+ result += jsonToTokenizedString(val, _key);
+ } else {
+ result += `${jsonToTokenizedString(val, _key)}, `;
+ }
+ });
+
+ result += ' }';
+ return result;
+ }
+
+ // This branch should never be reached
+ return '';
+}
+
+function stringToToken(str: string, keyProp: string, isBold?: boolean): ReactElement {
+ return isBold ? <b key={keyProp}>{str}</b> : <span key={keyProp}>{str}</span>;
+}
diff --git a/static/app/views/insights/database/views/databaseLandingPage.spec.tsx b/static/app/views/insights/database/views/databaseLandingPage.spec.tsx
index a16d650f047485..ff62f3462cfeb4 100644
--- a/static/app/views/insights/database/views/databaseLandingPage.spec.tsx
+++ b/static/app/views/insights/database/views/databaseLandingPage.spec.tsx
@@ -194,6 +194,7 @@ describe('DatabaseLandingPage', function () {
'project.id',
'span.group',
'span.description',
+ 'span.action',
'spm()',
'avg(span.self_time)',
'sum(span.self_time)',
@@ -310,6 +311,7 @@ describe('DatabaseLandingPage', function () {
'project.id',
'span.group',
'span.description',
+ 'span.action',
'spm()',
'avg(span.self_time)',
'sum(span.self_time)',
diff --git a/static/app/views/insights/database/views/databaseLandingPage.tsx b/static/app/views/insights/database/views/databaseLandingPage.tsx
index bae2e986d63fcb..c6f8e18289d147 100644
--- a/static/app/views/insights/database/views/databaseLandingPage.tsx
+++ b/static/app/views/insights/database/views/databaseLandingPage.tsx
@@ -107,6 +107,7 @@ export function DatabaseLandingPage() {
'project.id',
'span.group',
'span.description',
+ 'span.action',
'spm()',
'avg(span.self_time)',
'sum(span.self_time)',
@@ -221,7 +222,7 @@ export function DatabaseLandingPage() {
</ModuleLayout.Full>
<ModuleLayout.Full>
- <QueriesTable response={queryListResponse} sort={sort} />
+ <QueriesTable response={queryListResponse} sort={sort} system={system} />
</ModuleLayout.Full>
</ModulesOnboarding>
</ModuleLayout.Layout>
|
2a99b87b1f2f1beff3f48a279d461e976f9bcd5b
|
2019-04-25 17:36:37
|
Markus Unterwaditzer
|
fix: Check for None-ness of package (#12941)
| false
|
Check for None-ness of package (#12941)
|
fix
|
diff --git a/src/sentry/lang/native/symbolizer.py b/src/sentry/lang/native/symbolizer.py
index 9575743c1bbb90..ccda8ce97929ee 100644
--- a/src/sentry/lang/native/symbolizer.py
+++ b/src/sentry/lang/native/symbolizer.py
@@ -237,7 +237,7 @@ def symbolize_frame(self, instruction_addr, sdk_info=None,
# that just did not return any results but without error.
if app_err is not None \
and not match \
- and not is_known_third_party(obj.code_file, sdk_info=sdk_info):
+ and (not obj.code_file or not is_known_third_party(obj.code_file, sdk_info=sdk_info)):
raise app_err
return match
|
4665509b03188e30f1a4f04997b863462f37516f
|
2023-08-29 01:16:37
|
Malachi Willey
|
ref(tsc): Convert group test stub to typescript (#55222)
| false
|
Convert group test stub to typescript (#55222)
|
ref
|
diff --git a/fixtures/js-stubs/group.js b/fixtures/js-stubs/group.ts
similarity index 67%
rename from fixtures/js-stubs/group.js
rename to fixtures/js-stubs/group.ts
index 43f188dc6a2bd6..0b46a9e79d1a5d 100644
--- a/fixtures/js-stubs/group.js
+++ b/fixtures/js-stubs/group.ts
@@ -1,23 +1,33 @@
+import {
+ EventOrGroupType,
+ type Group as GroupType,
+ GroupStatus,
+ GroupUnresolved,
+ IssueCategory,
+ IssueType,
+} from 'sentry/types';
+
import {Project} from './project';
-export function Group(params = {}) {
+export function Group(params: Partial<GroupType> = {}): GroupType {
const project = Project();
- return {
+
+ const unresolvedGroup: GroupUnresolved = {
activity: [],
annotations: [],
assignedTo: null,
count: '327482',
culprit: 'fetchData(app/components/group/suggestedOwners/suggestedOwners)',
- firstRelease: null,
firstSeen: '2019-04-05T19:44:05.963Z',
+ filtered: null,
hasSeen: false,
id: '1',
isBookmarked: false,
isPublic: false,
isSubscribed: false,
- issueCategory: 'error',
- issueType: 'error',
- lastRelease: null,
+ isUnhandled: false,
+ issueCategory: IssueCategory.ERROR,
+ issueType: IssueType.ERROR,
lastSeen: '2019-04-11T01:08:59Z',
level: 'warning',
logger: null,
@@ -29,13 +39,13 @@ export function Group(params = {}) {
pluginActions: [],
pluginContexts: [],
pluginIssues: [],
- project: {
+ project: TestStubs.Project({
platform: 'javascript',
id: project.id,
slug: project.slug,
- },
+ }),
seenBy: [],
- shareId: null,
+ shareId: '',
shortId: 'JAVASCRIPT-6QS',
stats: {
'24h': [
@@ -47,15 +57,14 @@ export function Group(params = {}) {
[1515024000, 122],
],
},
- status: 'unresolved',
+ status: GroupStatus.UNRESOLVED,
statusDetails: {},
subscriptionDetails: null,
- // ex tag: {key: 'browser', name: 'Browser', totalValues: 1}
- tags: [],
title: 'RequestError: GET /issues/ 404',
- type: 'error',
+ type: EventOrGroupType.ERROR,
userCount: 35097,
userReportCount: 0,
- ...params,
};
+
+ return {...unresolvedGroup, ...params} as GroupType;
}
diff --git a/static/app/components/assigneeSelector.tsx b/static/app/components/assigneeSelector.tsx
index 3af4817b981faf..de01f4d4700caa 100644
--- a/static/app/components/assigneeSelector.tsx
+++ b/static/app/components/assigneeSelector.tsx
@@ -31,7 +31,7 @@ function AssigneeAvatar({
assignedTo,
suggestedActors = [],
}: {
- assignedTo?: Actor;
+ assignedTo?: Actor | null;
suggestedActors?: SuggestedAssignee[];
}) {
const suggestedReasons: Record<SuggestedOwnerReason, React.ReactNode> = {
diff --git a/static/app/components/assigneeSelectorDropdown.tsx b/static/app/components/assigneeSelectorDropdown.tsx
index c93da693c25f4f..fdb9c24465dc38 100644
--- a/static/app/components/assigneeSelectorDropdown.tsx
+++ b/static/app/components/assigneeSelectorDropdown.tsx
@@ -59,7 +59,7 @@ export interface AssigneeSelectorDropdownProps {
children: (props: RenderProps) => React.ReactNode;
id: string;
organization: Organization;
- assignedTo?: Actor;
+ assignedTo?: Actor | null;
disabled?: boolean;
memberList?: User[];
onAssign?: OnAssignCallback;
diff --git a/static/app/components/group/assignedTo.tsx b/static/app/components/group/assignedTo.tsx
index ed93baf9615092..cad17d6bc20d11 100644
--- a/static/app/components/group/assignedTo.tsx
+++ b/static/app/components/group/assignedTo.tsx
@@ -108,7 +108,7 @@ function getSuggestedReason(owner: IssueOwner) {
function getOwnerList(
committers: Committer[],
eventOwners: EventOwners | null,
- assignedTo: Actor
+ assignedTo: Actor | null
): Omit<SuggestedAssignee, 'assignee'>[] {
const owners: IssueOwner[] = committers.map(commiter => ({
actor: {...commiter.author, type: 'user'},
diff --git a/static/app/types/group.tsx b/static/app/types/group.tsx
index c8ae4016d4c567..95901d44044f76 100644
--- a/static/app/types/group.tsx
+++ b/static/app/types/group.tsx
@@ -575,7 +575,7 @@ export const enum GroupSubstatus {
export interface BaseGroup {
activity: GroupActivity[];
annotations: string[];
- assignedTo: Actor;
+ assignedTo: Actor | null;
culprit: string;
firstSeen: string;
hasSeen: boolean;
@@ -587,9 +587,8 @@ export interface BaseGroup {
issueCategory: IssueCategory;
issueType: IssueType;
lastSeen: string;
- latestEvent: Event;
level: Level;
- logger: string;
+ logger: string | null;
metadata: EventMetadata;
numComments: number;
participants: User[];
@@ -609,6 +608,7 @@ export interface BaseGroup {
type: EventOrGroupType;
userReportCount: number;
inbox?: InboxDetails | null | false;
+ latestEvent?: Event;
owners?: SuggestedOwner[] | null;
substatus?: GroupSubstatus | null;
}
diff --git a/static/app/views/issueDetails/groupDetails.spec.tsx b/static/app/views/issueDetails/groupDetails.spec.tsx
index e0700837eb471c..784dcc813cc216 100644
--- a/static/app/views/issueDetails/groupDetails.spec.tsx
+++ b/static/app/views/issueDetails/groupDetails.spec.tsx
@@ -270,8 +270,6 @@ describe('groupDetails', () => {
});
it('renders alert for sample event', async function () {
- const sampleGroup = TestStubs.Group({issueCategory: IssueCategory.ERROR});
- sampleGroup.tags.push({key: 'sample_event'});
MockApiClient.addMockResponse({
url: `/issues/${group.id}/tags/`,
body: [{key: 'sample_event'}],
|
08addf3d04b61c8f73f5b9c025235b77165e8467
|
2025-02-20 01:21:59
|
Andrew Liu
|
feat(flags): add statsig onboarding snippets and refactor onboarding components (#85419)
| false
|
add statsig onboarding snippets and refactor onboarding components (#85419)
|
feat
|
diff --git a/static/app/components/events/featureFlags/featureFlagOnboardingSidebar.tsx b/static/app/components/events/featureFlags/featureFlagOnboardingSidebar.tsx
index 3b2339ec17f64d..f58a9a72ac9592 100644
--- a/static/app/components/events/featureFlags/featureFlagOnboardingSidebar.tsx
+++ b/static/app/components/events/featureFlags/featureFlagOnboardingSidebar.tsx
@@ -10,8 +10,8 @@ import {FeatureFlagOnboardingLayout} from 'sentry/components/events/featureFlags
import {FeatureFlagOtherPlatformOnboarding} from 'sentry/components/events/featureFlags/featureFlagOtherPlatformOnboarding';
import {FLAG_HASH_SKIP_CONFIG} from 'sentry/components/events/featureFlags/useFeatureFlagOnboarding';
import {
- IntegrationOptions,
- ProviderOptions,
+ SdkProviderEnum,
+ WebhookProviderEnum,
} from 'sentry/components/events/featureFlags/utils';
import RadioGroup from 'sentry/components/forms/controls/radioGroup';
import useDrawer from 'sentry/components/globalDrawer';
@@ -204,11 +204,9 @@ function OnboardingContent({
return window.location.hash;
}, []);
const skipConfig = ORIGINAL_HASH === FLAG_HASH_SKIP_CONFIG;
- const openFeatureProviders = Object.values(ProviderOptions);
- const sdkProviders = Object.values(ProviderOptions);
// First dropdown: OpenFeature providers
- const openFeatureProviderOptions = openFeatureProviders.map(provider => {
+ const openFeatureProviderOptions = Object.values(WebhookProviderEnum).map(provider => {
return {
value: provider,
textValue: provider,
@@ -223,13 +221,15 @@ function OnboardingContent({
}>(openFeatureProviderOptions[0]!);
// Second dropdown: other SDK providers
- const sdkProviderOptions = sdkProviders.map(provider => {
- return {
- value: provider,
- textValue: provider,
- label: <TextOverflow>{provider}</TextOverflow>,
- };
- });
+ const sdkProviderOptions = Object.values(SdkProviderEnum)
+ .filter(provider => provider !== SdkProviderEnum.OPENFEATURE)
+ .map(provider => {
+ return {
+ value: provider,
+ textValue: provider,
+ label: <TextOverflow>{provider}</TextOverflow>,
+ };
+ });
const [sdkProvider, setsdkProvider] = useState<{
value: string;
@@ -356,7 +356,7 @@ function OnboardingContent({
integration={
// either OpenFeature or the SDK selected from the second dropdown
setupMode() === 'openFeature'
- ? IntegrationOptions.OPENFEATURE
+ ? SdkProviderEnum.OPENFEATURE
: sdkProvider.value
}
provider={
@@ -394,9 +394,7 @@ function OnboardingContent({
projectSlug={currentProject.slug}
integration={
// either OpenFeature or the SDK selected from the second dropdown
- setupMode() === 'openFeature'
- ? IntegrationOptions.OPENFEATURE
- : sdkProvider.value
+ setupMode() === 'openFeature' ? SdkProviderEnum.OPENFEATURE : sdkProvider.value
}
provider={
// dropdown value (from either dropdown)
diff --git a/static/app/components/events/featureFlags/onboardingIntegrationSection.tsx b/static/app/components/events/featureFlags/onboardingIntegrationSection.tsx
index afb0f0cfc8a8a2..c5063ce0b1fc08 100644
--- a/static/app/components/events/featureFlags/onboardingIntegrationSection.tsx
+++ b/static/app/components/events/featureFlags/onboardingIntegrationSection.tsx
@@ -11,8 +11,8 @@ import {Button} from 'sentry/components/button';
import {Flex} from 'sentry/components/container/flex';
import {Alert} from 'sentry/components/core/alert';
import {
- PROVIDER_OPTION_TO_URLS,
- ProviderOptions,
+ PROVIDER_TO_SETUP_WEBHOOK_URL,
+ WebhookProviderEnum,
} from 'sentry/components/events/featureFlags/utils';
import Input from 'sentry/components/input';
import ExternalLink from 'sentry/components/links/externalLink';
@@ -120,7 +120,9 @@ export default function OnboardingIntegrationSection({
{
link: (
<ExternalLink
- href={PROVIDER_OPTION_TO_URLS[provider as ProviderOptions]}
+ href={
+ PROVIDER_TO_SETUP_WEBHOOK_URL[provider as WebhookProviderEnum]
+ }
/>
),
}
@@ -138,7 +140,7 @@ export default function OnboardingIntegrationSection({
</SubSection>
<SubSection>
<div>
- {provider === ProviderOptions.UNLEASH
+ {provider === WebhookProviderEnum.UNLEASH
? t(
`During the process of creating a webhook integration, you'll be given the option to add an authorization header. This is a string (or "secret") that you choose so that Sentry can verify requests from your feature flag service. Paste your authorization string below.`
)
diff --git a/static/app/components/events/featureFlags/utils.tsx b/static/app/components/events/featureFlags/utils.tsx
index 8a7907dc5f7ea6..dbebe95d470adc 100644
--- a/static/app/components/events/featureFlags/utils.tsx
+++ b/static/app/components/events/featureFlags/utils.tsx
@@ -113,24 +113,30 @@ export const sortedFlags = ({
}
};
-export enum ProviderOptions {
+// Supported Feature Flag Providers. Ordered by display order in FeatureFlagOnboardingDrawer. We prefer Generic to be last.
+export enum WebhookProviderEnum {
LAUNCHDARKLY = 'LaunchDarkly',
- GENERIC = 'Generic',
+ STATSIG = 'Statsig',
UNLEASH = 'Unleash',
+ GENERIC = 'Generic',
}
-export enum IntegrationOptions {
+// Supported Feature Flag SDKs. Ordered by display order in FeatureFlagOnboardingDrawer. We prefer Generic to be last.
+export enum SdkProviderEnum {
LAUNCHDARKLY = 'LaunchDarkly',
OPENFEATURE = 'OpenFeature',
- GENERIC = 'Generic',
+ STATSIG = 'Statsig',
UNLEASH = 'Unleash',
+ GENERIC = 'Generic',
}
-export const PROVIDER_OPTION_TO_URLS: Record<ProviderOptions, string | undefined> = {
- [ProviderOptions.LAUNCHDARKLY]:
+export const PROVIDER_TO_SETUP_WEBHOOK_URL: Record<WebhookProviderEnum, string> = {
+ [WebhookProviderEnum.GENERIC]:
+ 'https://docs.sentry.io/organization/integrations/feature-flag/generic/#set-up-change-tracking',
+ [WebhookProviderEnum.LAUNCHDARKLY]:
'https://app.launchdarkly.com/settings/integrations/webhooks/new?q=Webhooks',
- [ProviderOptions.UNLEASH]:
+ [WebhookProviderEnum.STATSIG]:
+ 'https://docs.sentry.io/organization/integrations/feature-flag/statsig/#set-up-change-tracking',
+ [WebhookProviderEnum.UNLEASH]:
'https://docs.sentry.io/organization/integrations/feature-flag/unleash/#set-up-change-tracking',
- [ProviderOptions.GENERIC]:
- 'https://docs.sentry.io/organization/integrations/feature-flag/generic/#set-up-change-tracking',
};
diff --git a/static/app/gettingStartedDocs/javascript/javascript.tsx b/static/app/gettingStartedDocs/javascript/javascript.tsx
index 8e85c5c6082328..2ee2fad6843847 100644
--- a/static/app/gettingStartedDocs/javascript/javascript.tsx
+++ b/static/app/gettingStartedDocs/javascript/javascript.tsx
@@ -1,6 +1,6 @@
import {css} from '@emotion/react';
-import {IntegrationOptions} from 'sentry/components/events/featureFlags/utils';
+import {SdkProviderEnum as FeatureFlagProviderEnum} from 'sentry/components/events/featureFlags/utils';
import ExternalLink from 'sentry/components/links/externalLink';
import crashReportCallout from 'sentry/components/onboarding/gettingStartedDoc/feedback/crashReportCallout';
import widgetCallout from 'sentry/components/onboarding/gettingStartedDoc/feedback/widgetCallout';
@@ -64,38 +64,111 @@ const platformOptions = {
type PlatformOptions = typeof platformOptions;
type Params = DocsParams<PlatformOptions>;
-type FlagOptions = {
- importStatement: string; // feature flag SDK import
- integration: string; // what's in the integrations array
- sdkInit: string; // code to register with feature flag SDK
+
+type FeatureFlagConfiguration = {
+ integrationName: string;
+ makeCodeSnippet: (dsn: string) => string;
};
-const FLAG_OPTIONS: Record<IntegrationOptions, FlagOptions> = {
- [IntegrationOptions.LAUNCHDARKLY]: {
- importStatement: `import * as LaunchDarkly from 'launchdarkly-js-client-sdk';`,
- integration: 'launchDarklyIntegration()',
- sdkInit: `const ldClient = LaunchDarkly.initialize(
- 'my-client-ID',
- {kind: 'user', key: 'my-user-context-key'},
- {inspectors: [Sentry.buildLaunchDarklyFlagUsedHandler()]}
+const FEATURE_FLAG_CONFIGURATION_MAP: Record<
+ FeatureFlagProviderEnum,
+ FeatureFlagConfiguration
+> = {
+ [FeatureFlagProviderEnum.GENERIC]: {
+ integrationName: `featureFlagsIntegration`,
+ makeCodeSnippet: (dsn: string) => `import * as Sentry from "@sentry/browser";
+
+Sentry.init({
+ dsn: "${dsn}",
+ integrations: [Sentry.featureFlagsIntegration()],
+});
+
+const flagsIntegration = Sentry.getClient()?.getIntegrationByName<Sentry.FeatureFlagsIntegration>("FeatureFlags");
+if (flagsIntegration) {
+ flagsIntegration.addFeatureFlag("test-flag", false);
+} else {
+ // Something went wrong, check your DSN and/or integrations
+}
+Sentry.captureException(new Error("Something went wrong!"));`,
+ },
+
+ [FeatureFlagProviderEnum.LAUNCHDARKLY]: {
+ integrationName: `launchDarklyIntegration`,
+ makeCodeSnippet: (dsn: string) => `import * as Sentry from "@sentry/browser";
+import * as LaunchDarkly from "launchdarkly-js-client-sdk";
+
+Sentry.init({
+ dsn: "${dsn}",
+ integrations: [Sentry.launchDarklyIntegration()],
+});
+
+const ldClient = LaunchDarkly.initialize(
+ "my-client-ID",
+ { kind: "user", key: "my-user-context-key" },
+ { inspectors: [Sentry.buildLaunchDarklyFlagUsedHandler()] },
);
-// Evaluates a flag
-const flagVal = ldClient.variation('my-flag', false);`,
+// Evaluate a flag with a default value. You may have to wait for your client to initialize first.
+ldClient?.variation("test-flag", false);
+
+Sentry.captureException(new Error("Something went wrong!"));`,
},
- [IntegrationOptions.OPENFEATURE]: {
- importStatement: `import { OpenFeature } from '@openfeature/web-sdk';`,
- integration: 'openFeatureIntegration()',
- sdkInit: `const client = OpenFeature.getClient();
-client.addHooks(new Sentry.OpenFeatureIntegrationHook());
-
-// Evaluating flags will record the result on the Sentry client.
-const result = client.getBooleanValue('my-flag', false);`,
+
+ [FeatureFlagProviderEnum.OPENFEATURE]: {
+ integrationName: `openFeatureIntegration`,
+ makeCodeSnippet: (dsn: string) => `import * as Sentry from "@sentry/browser";
+import { OpenFeature } from "@openfeature/web-sdk";
+
+Sentry.init({
+ dsn: "${dsn}",
+ integrations: [Sentry.openFeatureIntegration()],
+});
+
+OpenFeature.setProvider(new MyProviderOfChoice());
+OpenFeature.addHooks(new Sentry.OpenFeatureIntegrationHook());
+
+const client = OpenFeature.getClient();
+const result = client.getBooleanValue("test-flag", false); // evaluate with a default value
+Sentry.captureException(new Error("Something went wrong!"));`,
},
- [IntegrationOptions.UNLEASH]: {
- importStatement: `import { UnleashClient } from 'unleash-proxy-client';`,
- integration: 'unleashIntegration({unleashClientClass: UnleashClient})',
- sdkInit: `const unleash = new UnleashClient({
+
+ [FeatureFlagProviderEnum.STATSIG]: {
+ integrationName: `statsigIntegration`,
+ makeCodeSnippet: (dsn: string) => `import * as Sentry from "@sentry/browser";
+import { StatsigClient } from "@statsig/js-client";
+
+const statsigClient = new StatsigClient(
+ YOUR_SDK_KEY,
+ { userID: "my-user-id" },
+ {},
+); // see Statsig SDK reference.
+
+Sentry.init({
+ dsn: "${dsn}",
+ integrations: [
+ Sentry.statsigIntegration({ featureFlagClient: statsigClient }),
+ ],
+});
+
+await statsigClient.initializeAsync(); // or statsigClient.initializeSync();
+
+const result = statsigClient.checkGate("my-feature-gate");
+Sentry.captureException(new Error("something went wrong"));`,
+ },
+
+ [FeatureFlagProviderEnum.UNLEASH]: {
+ integrationName: `unleashIntegration`,
+ makeCodeSnippet: (dsn: string) => `import * as Sentry from "@sentry/browser";
+import { UnleashClient } from "unleash-proxy-client";
+
+Sentry.init({
+ dsn: "${dsn}",
+ integrations: [
+ Sentry.unleashIntegration({ unleashClientClass: UnleashClient }),
+ ],
+});
+
+const unleash = new UnleashClient({
url: "https://<your-unleash-instance>/api/frontend",
clientKey: "<your-client-side-token>",
appName: "my-webapp",
@@ -108,19 +181,6 @@ unleash.isEnabled("test-flag");
Sentry.captureException(new Error("Something went wrong!"));`,
},
- [IntegrationOptions.GENERIC]: {
- importStatement: ``,
- integration: 'featureFlagsIntegration()',
- sdkInit: `const flagsIntegration = Sentry.getClient()?.getIntegrationByName<Sentry.FeatureFlagsIntegration>('FeatureFlags');
-
-if (flagsIntegration) {
- flagsIntegration.addFeatureFlag('test-flag', false);
-} else {
- // Something went wrong, check your DSN and/or integrations
-}
-
-Sentry.captureException(new Error('Something went wrong!'));`,
- },
};
const isAutoInstall = (params: Params) =>
@@ -675,38 +735,29 @@ const profilingOnboarding: OnboardingConfig<PlatformOptions> = {
export const featureFlagOnboarding: OnboardingConfig = {
install: () => [],
- configure: ({featureFlagOptions = {integration: ''}, dsn}) => [
- {
- type: StepType.CONFIGURE,
- description: tct(
- 'Add [name] to your integrations list, and then register with your feature flag SDK.',
- {
- name: (
- <code>{`${FLAG_OPTIONS[featureFlagOptions.integration as keyof typeof FLAG_OPTIONS].integration}`}</code>
- ),
- }
- ),
- configurations: [
- {
- language: 'JavaScript',
- code: `
-${FLAG_OPTIONS[featureFlagOptions.integration as keyof typeof FLAG_OPTIONS].importStatement}
-
-// Register with Sentry
-Sentry.init({
- dsn: "${dsn.public}",
- integrations: [
- Sentry.${FLAG_OPTIONS[featureFlagOptions.integration as keyof typeof FLAG_OPTIONS].integration},
- ],
-});
-
-// Register with your feature flag SDK
-${FLAG_OPTIONS[featureFlagOptions.integration as keyof typeof FLAG_OPTIONS].sdkInit}
-`,
- },
- ],
- },
- ],
+ configure: ({featureFlagOptions = {integration: ''}, dsn}) => {
+ const {integrationName, makeCodeSnippet} =
+ FEATURE_FLAG_CONFIGURATION_MAP[
+ featureFlagOptions.integration as keyof typeof FEATURE_FLAG_CONFIGURATION_MAP
+ ]!;
+ return [
+ {
+ type: StepType.CONFIGURE,
+ description: tct(
+ 'Add [name] to your integrations list, and initialize your feature flag SDK.',
+ {
+ name: <code>{integrationName}</code>,
+ }
+ ),
+ configurations: [
+ {
+ language: 'JavaScript',
+ code: `${makeCodeSnippet(dsn.public)}`,
+ },
+ ],
+ },
+ ];
+ },
verify: () => [],
nextSteps: () => [],
};
diff --git a/static/app/gettingStartedDocs/python/python.tsx b/static/app/gettingStartedDocs/python/python.tsx
index 33a998396bd2f4..fa3d7954bdb4de 100644
--- a/static/app/gettingStartedDocs/python/python.tsx
+++ b/static/app/gettingStartedDocs/python/python.tsx
@@ -1,4 +1,4 @@
-import {IntegrationOptions} from 'sentry/components/events/featureFlags/utils';
+import {SdkProviderEnum as FeatureFlagProviderEnum} from 'sentry/components/events/featureFlags/utils';
import ExternalLink from 'sentry/components/links/externalLink';
import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step';
import {
@@ -16,27 +16,109 @@ import {t, tct} from 'sentry/locale';
type Params = DocsParams;
-type FlagImports = {
- integration: string; // what's in the integrations array
- module: string; // what's imported from sentry_sdk.integrations
+type FeatureFlagConfiguration = {
+ integrationName: string;
+ makeCodeSnippet: (dsn: string) => string;
};
-const FLAG_OPTION_TO_IMPORT: Record<IntegrationOptions, FlagImports> = {
- [IntegrationOptions.LAUNCHDARKLY]: {
- module: 'integrations.launchdarkly',
- integration: 'LaunchDarklyIntegration',
+const FEATURE_FLAG_CONFIGURATION_MAP: Record<
+ FeatureFlagProviderEnum,
+ FeatureFlagConfiguration
+> = {
+ [FeatureFlagProviderEnum.GENERIC]: {
+ integrationName: ``,
+ makeCodeSnippet: (_dsn: string) => `import sentry_sdk
+from sentry_sdk.feature_flags import add_feature_flag
+
+add_feature_flag('test-flag', False) # Records an evaluation and its result.
+sentry_sdk.capture_exception(Exception("Something went wrong!"))`,
+ },
+
+ [FeatureFlagProviderEnum.LAUNCHDARKLY]: {
+ integrationName: `LaunchDarklyIntegration`,
+ makeCodeSnippet: (dsn: string) => `import sentry_sdk
+from sentry_sdk.integrations.launchdarkly import LaunchDarklyIntegration
+import ldclient
+
+sentry_sdk.init(
+ dsn="${dsn}",
+ # Add data like request headers and IP for users, if applicable;
+ # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info
+ send_default_pii=True,
+ integrations=[
+ LaunchDarklyIntegration(),
+ ],
+)
+
+client = ldclient.get()
+client.variation("hello", Context.create("test-context"), False) # Evaluate a flag with a default value.
+sentry_sdk.capture_exception(Exception("Something went wrong!"))`,
},
- [IntegrationOptions.OPENFEATURE]: {
- module: 'integrations.openfeature',
- integration: 'OpenFeatureIntegration',
+
+ [FeatureFlagProviderEnum.OPENFEATURE]: {
+ integrationName: `OpenFeatureIntegration`,
+ makeCodeSnippet: (dsn: string) => `import sentry_sdk
+from sentry_sdk.integrations.openfeature import OpenFeatureIntegration
+from openfeature import api
+
+sentry_sdk.init(
+ dsn="${dsn}",
+ # Add data like request headers and IP for users, if applicable;
+ # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info
+ send_default_pii=True,
+ integrations=[
+ OpenFeatureIntegration(),
+ ],
+)
+
+client = api.get_client()
+client.get_boolean_value("hello", default_value=False) # Evaluate a flag with a default value.
+sentry_sdk.capture_exception(Exception("Something went wrong!"))`,
},
- [IntegrationOptions.UNLEASH]: {
- module: 'integrations.unleash',
- integration: 'UnleashIntegration',
+
+ [FeatureFlagProviderEnum.STATSIG]: {
+ integrationName: `StatsigIntegration`,
+ makeCodeSnippet: (dsn: string) => `import sentry_sdk
+from sentry_sdk.integrations.statsig import StatsigIntegration
+from statsig.statsig_user import StatsigUser
+from statsig import statsig
+import time
+
+sentry_sdk.init(
+ dsn="${dsn}",
+ # Add data like request headers and IP for users, if applicable;
+ # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info
+ send_default_pii=True,
+ integrations=[StatsigIntegration()],
+)
+
+statsig.initialize("server-secret-key")
+while not statsig.is_initialized():
+ time.sleep(0.2)
+
+result = statsig.check_gate(StatsigUser("my-user-id"), "my-feature-gate") # Evaluate a flag.
+sentry_sdk.capture_exception(Exception("Something went wrong!"))`,
},
- [IntegrationOptions.GENERIC]: {
- module: 'feature_flags',
- integration: '',
+
+ [FeatureFlagProviderEnum.UNLEASH]: {
+ integrationName: `UnleashIntegration`,
+ makeCodeSnippet: (dsn: string) => `import sentry_sdk
+from sentry_sdk.integrations.unleash import UnleashIntegration
+from UnleashClient import UnleashClient
+
+sentry_sdk.init(
+ dsn="${dsn}",
+ # Add data like request headers and IP for users, if applicable;
+ # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info
+ send_default_pii=True,
+ integrations=[UnleashIntegration()],
+)
+
+unleash = UnleashClient(...) # See Unleash quickstart.
+unleash.initialize_client()
+
+test_flag_enabled = unleash.is_enabled("test-flag") # Evaluate a flag.
+sentry_sdk.capture_exception(Exception("Something went wrong!"))`,
},
};
@@ -255,44 +337,29 @@ export function AlternativeConfiguration() {
export const featureFlagOnboarding: OnboardingConfig = {
install: () => [],
- configure: ({featureFlagOptions = {integration: ''}, dsn}) => [
- {
- type: StepType.CONFIGURE,
- description:
- featureFlagOptions.integration === IntegrationOptions.GENERIC
- ? `This provider doesn't use an integration. Simply initialize Sentry and import the API.`
- : tct('Add [name] to your integrations list.', {
- name: (
- <code>{`${FLAG_OPTION_TO_IMPORT[featureFlagOptions.integration as keyof typeof FLAG_OPTION_TO_IMPORT].integration}()`}</code>
- ),
- }),
- configurations: [
- {
- language: 'python',
- code:
- featureFlagOptions.integration === IntegrationOptions.GENERIC
- ? `import sentry_sdk
-from sentry_sdk.${FLAG_OPTION_TO_IMPORT[featureFlagOptions.integration].module} import add_feature_flag
-
-sentry_sdk.init(
- dsn="${dsn.public}",
- integrations=[
- # your other integrations here
- ]
-)`
- : `import sentry_sdk
-from sentry_sdk.${FLAG_OPTION_TO_IMPORT[featureFlagOptions.integration as keyof typeof FLAG_OPTION_TO_IMPORT].module} import ${FLAG_OPTION_TO_IMPORT[featureFlagOptions.integration as keyof typeof FLAG_OPTION_TO_IMPORT].integration}
-
-sentry_sdk.init(
- dsn="${dsn.public}",
- integrations=[
- ${FLAG_OPTION_TO_IMPORT[featureFlagOptions.integration as keyof typeof FLAG_OPTION_TO_IMPORT].integration}(),
- ]
-)`,
- },
- ],
- },
- ],
+ configure: ({featureFlagOptions = {integration: ''}, dsn}) => {
+ const {integrationName, makeCodeSnippet} =
+ FEATURE_FLAG_CONFIGURATION_MAP[
+ featureFlagOptions.integration as keyof typeof FEATURE_FLAG_CONFIGURATION_MAP
+ ]!;
+ return [
+ {
+ type: StepType.CONFIGURE,
+ description:
+ featureFlagOptions.integration === FeatureFlagProviderEnum.GENERIC
+ ? `You don't need an integration for a generic usecase. Simply use this API after initializing Sentry.`
+ : tct('Add [name] to your integrations list.', {
+ name: <code>{`${integrationName}`}</code>,
+ }),
+ configurations: [
+ {
+ language: 'python',
+ code: makeCodeSnippet(dsn.public),
+ },
+ ],
+ },
+ ];
+ },
verify: () => [],
nextSteps: () => [],
};
diff --git a/static/app/views/settings/featureFlags/newProviderForm.tsx b/static/app/views/settings/featureFlags/newProviderForm.tsx
index a95519bbaf8acd..9af46fae723765 100644
--- a/static/app/views/settings/featureFlags/newProviderForm.tsx
+++ b/static/app/views/settings/featureFlags/newProviderForm.tsx
@@ -7,7 +7,7 @@ import {
addSuccessMessage,
} from 'sentry/actionCreators/indicator';
import {hasEveryAccess} from 'sentry/components/acl/access';
-import {PROVIDER_OPTION_TO_URLS} from 'sentry/components/events/featureFlags/utils';
+import {PROVIDER_TO_SETUP_WEBHOOK_URL} from 'sentry/components/events/featureFlags/utils';
import FieldGroup from 'sentry/components/forms/fieldGroup';
import SelectField from 'sentry/components/forms/fields/selectField';
import TextField from 'sentry/components/forms/fields/textField';
@@ -131,7 +131,7 @@ export default function NewProviderForm({
"Create a webhook integration with your [link:feature flag service]. When you do so, you'll need to enter this URL.",
{
// @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
- link: <ExternalLink href={PROVIDER_OPTION_TO_URLS[selectedProvider]} />,
+ link: <ExternalLink href={PROVIDER_TO_SETUP_WEBHOOK_URL[selectedProvider]} />,
}
)}
inline
diff --git a/static/app/views/settings/featureFlags/newSecretHandler.tsx b/static/app/views/settings/featureFlags/newSecretHandler.tsx
index 3c4fd373a4345b..45929f1b66eafe 100644
--- a/static/app/views/settings/featureFlags/newSecretHandler.tsx
+++ b/static/app/views/settings/featureFlags/newSecretHandler.tsx
@@ -3,7 +3,7 @@ import styled from '@emotion/styled';
import {Button} from 'sentry/components/button';
import {Alert} from 'sentry/components/core/alert';
-import {PROVIDER_OPTION_TO_URLS} from 'sentry/components/events/featureFlags/utils';
+import {PROVIDER_TO_SETUP_WEBHOOK_URL} from 'sentry/components/events/featureFlags/utils';
import FieldGroup from 'sentry/components/forms/fieldGroup';
import ExternalLink from 'sentry/components/links/externalLink';
import PanelItem from 'sentry/components/panels/panelItem';
@@ -37,8 +37,13 @@ function NewSecretHandler({
"Create a webhook integration with your [link:feature flag service]. When you do so, you'll need to enter this URL.",
{
link: (
- // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
- <ExternalLink href={PROVIDER_OPTION_TO_URLS[provider.toLowerCase()]} />
+ <ExternalLink
+ href={
+ PROVIDER_TO_SETUP_WEBHOOK_URL[
+ provider.toLowerCase() as keyof typeof PROVIDER_TO_SETUP_WEBHOOK_URL
+ ]
+ }
+ />
),
}
)}
|
bcb9d9d444652d93ff6fcf30b425195fc5fe41cb
|
2024-12-30 22:42:49
|
edwardgou-sentry
|
fix(insights): update to handle when there are no value segments provided to the score ring (#82649)
| false
|
update to handle when there are no value segments provided to the score ring (#82649)
|
fix
|
diff --git a/static/app/views/insights/browser/webVitals/components/performanceScoreRing.tsx b/static/app/views/insights/browser/webVitals/components/performanceScoreRing.tsx
index 765cdd70e3a7b6..c4cc513ebd7655 100644
--- a/static/app/views/insights/browser/webVitals/components/performanceScoreRing.tsx
+++ b/static/app/views/insights/browser/webVitals/components/performanceScoreRing.tsx
@@ -76,14 +76,17 @@ function PerformanceScoreRing({
const ringSegmentPadding = values.length > 1 ? PADDING : 0;
// TODO: Hacky way to add padding to ring segments. Should clean this up so it's more accurate to the value.
// This only mostly works because we expect values to be somewhere between 0 and 100.
- const maxOffset =
- (1 - Math.max(maxValue - ringSegmentPadding, 0) / sumMaxValues) * circumference;
- const progressOffset =
- (1 - Math.max(boundedValue - ringSegmentPadding, 0) / sumMaxValues) *
- circumference;
+ const maxOffset = sumMaxValues
+ ? (1 - Math.max(maxValue - ringSegmentPadding, 0) / sumMaxValues) * circumference
+ : 0;
+ const progressOffset = sumMaxValues
+ ? (1 - Math.max(boundedValue - ringSegmentPadding, 0) / sumMaxValues) *
+ circumference
+ : 0;
const rotate = currentRotate;
- currentRotate += (360 * maxValue) / sumMaxValues;
-
+ if (sumMaxValues) {
+ currentRotate += (360 * maxValue) / sumMaxValues;
+ }
const cx = radius + barWidth / 2;
return [
|
1c3377cf37491ee2093d58ab214334fe7c1c4ac1
|
2017-10-13 05:57:06
|
Billy Vong
|
feat(ui): Remove "other fingerprints" from merged events (#6322)
| false
|
Remove "other fingerprints" from merged events (#6322)
|
feat
|
diff --git a/src/sentry/static/sentry/app/views/groupMerged/mergedItem.jsx b/src/sentry/static/sentry/app/views/groupMerged/mergedItem.jsx
index 50617b290f7f99..ba4158ba124204 100644
--- a/src/sentry/static/sentry/app/views/groupMerged/mergedItem.jsx
+++ b/src/sentry/static/sentry/app/views/groupMerged/mergedItem.jsx
@@ -117,6 +117,7 @@ const MergedItem = React.createClass({
{event &&
<SpreadLayout className="event-details" responsive>
+
<FlowLayout>
<EventOrGroupHeader
orgId={orgId}
@@ -127,20 +128,6 @@ const MergedItem = React.createClass({
/>
</FlowLayout>
- <FlowLayout vertical style={{alignItems: 'flex-end'}}>
- <span className="fingerprint-header">
- Other Fingerprints
- </span>
-
- <FlowLayout>
- {event.fingerprints.filter(fp => fp !== fingerprint).map(fp => (
- <span key={fp} className="fingerprint">
- {fp}
- </span>
- ))}
- </FlowLayout>
- </FlowLayout>
-
</SpreadLayout>}
</div>}
</div>
diff --git a/tests/js/spec/views/__snapshots__/groupMergedView.spec.jsx.snap b/tests/js/spec/views/__snapshots__/groupMergedView.spec.jsx.snap
index 7e360dc1cbccc2..eec95158345fd7 100644
--- a/tests/js/spec/views/__snapshots__/groupMergedView.spec.jsx.snap
+++ b/tests/js/spec/views/__snapshots__/groupMergedView.spec.jsx.snap
@@ -896,43 +896,6 @@ exports[`Issues -> Merged View renders with mocked data 1`] = `
</EventOrGroupHeader>
</div>
</FlowLayout>
- <FlowLayout
- style={
- Object {
- "alignItems": "flex-end",
- }
- }
- truncate={true}
- vertical={true}
- >
- <div
- className="flow-layout is-vertical is-truncated"
- style={
- Object {
- "alignItems": "flex-end",
- }
- }
- >
- <span
- className="fingerprint-header"
- >
- Other Fingerprints
- </span>
- <FlowLayout
- truncate={true}
- >
- <div
- className="flow-layout is-truncated"
- >
- <span
- className="fingerprint"
- >
- e05da55328a860b21f62e371f0a7507d
- </span>
- </div>
- </FlowLayout>
- </div>
- </FlowLayout>
</div>
</SpreadLayout>
</div>
@@ -1361,43 +1324,6 @@ exports[`Issues -> Merged View renders with mocked data 1`] = `
</EventOrGroupHeader>
</div>
</FlowLayout>
- <FlowLayout
- style={
- Object {
- "alignItems": "flex-end",
- }
- }
- truncate={true}
- vertical={true}
- >
- <div
- className="flow-layout is-vertical is-truncated"
- style={
- Object {
- "alignItems": "flex-end",
- }
- }
- >
- <span
- className="fingerprint-header"
- >
- Other Fingerprints
- </span>
- <FlowLayout
- truncate={true}
- >
- <div
- className="flow-layout is-truncated"
- >
- <span
- className="fingerprint"
- >
- 2c4887696f708c476a81ce4e834c4b02
- </span>
- </div>
- </FlowLayout>
- </div>
- </FlowLayout>
</div>
</SpreadLayout>
</div>
@@ -2293,43 +2219,6 @@ exports[`Issues -> Merged View renders with mocked data 2`] = `
</EventOrGroupHeader>
</div>
</FlowLayout>
- <FlowLayout
- style={
- Object {
- "alignItems": "flex-end",
- }
- }
- truncate={true}
- vertical={true}
- >
- <div
- className="flow-layout is-vertical is-truncated"
- style={
- Object {
- "alignItems": "flex-end",
- }
- }
- >
- <span
- className="fingerprint-header"
- >
- Other Fingerprints
- </span>
- <FlowLayout
- truncate={true}
- >
- <div
- className="flow-layout is-truncated"
- >
- <span
- className="fingerprint"
- >
- e05da55328a860b21f62e371f0a7507d
- </span>
- </div>
- </FlowLayout>
- </div>
- </FlowLayout>
</div>
</SpreadLayout>
</div>
@@ -2758,43 +2647,6 @@ exports[`Issues -> Merged View renders with mocked data 2`] = `
</EventOrGroupHeader>
</div>
</FlowLayout>
- <FlowLayout
- style={
- Object {
- "alignItems": "flex-end",
- }
- }
- truncate={true}
- vertical={true}
- >
- <div
- className="flow-layout is-vertical is-truncated"
- style={
- Object {
- "alignItems": "flex-end",
- }
- }
- >
- <span
- className="fingerprint-header"
- >
- Other Fingerprints
- </span>
- <FlowLayout
- truncate={true}
- >
- <div
- className="flow-layout is-truncated"
- >
- <span
- className="fingerprint"
- >
- 2c4887696f708c476a81ce4e834c4b02
- </span>
- </div>
- </FlowLayout>
- </div>
- </FlowLayout>
</div>
</SpreadLayout>
</div>
|
4b0efe0cbec2b7c630a3a4b241a8c4bbfca04f1d
|
2022-06-02 20:12:22
|
Daian Scuarissi
|
feat(replays): add 'Share' button in header to deeplink timestamp (#35095)
| false
|
add 'Share' button in header to deeplink timestamp (#35095)
|
feat
|
diff --git a/static/app/utils/replays/createUrlToShare.tsx b/static/app/utils/replays/createUrlToShare.tsx
new file mode 100644
index 00000000000000..97e012b6dee1be
--- /dev/null
+++ b/static/app/utils/replays/createUrlToShare.tsx
@@ -0,0 +1,14 @@
+function createUrlToShare(currentTimeMs: number) {
+ const url = new URL(window.location.href);
+ const currentTimeSec = Math.floor(msToSec(currentTimeMs) || 0);
+ if (currentTimeSec > 0) {
+ url.searchParams.set('t', currentTimeSec.toString());
+ }
+ return url.toString();
+}
+
+function msToSec(ms: number) {
+ return ms / 1000;
+}
+
+export default createUrlToShare;
diff --git a/static/app/views/replays/detail/detailLayout.tsx b/static/app/views/replays/detail/detailLayout.tsx
index fd50cb691ecf64..1aa527a5b5365b 100644
--- a/static/app/views/replays/detail/detailLayout.tsx
+++ b/static/app/views/replays/detail/detailLayout.tsx
@@ -1,7 +1,9 @@
-import React from 'react';
+import React, {useMemo} from 'react';
import styled from '@emotion/styled';
import Breadcrumbs from 'sentry/components/breadcrumbs';
+import Button from 'sentry/components/button';
+import Clipboard from 'sentry/components/clipboard';
import Duration from 'sentry/components/duration';
import FeatureBadge from 'sentry/components/featureBadge';
import {FeatureFeedback} from 'sentry/components/featureFeedback';
@@ -12,10 +14,13 @@ import {KeyMetricData, KeyMetrics} from 'sentry/components/replays/keyMetrics';
import {useReplayContext} from 'sentry/components/replays/replayContext';
import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
import TimeSince from 'sentry/components/timeSince';
+import {IconLink} from 'sentry/icons';
import {t} from 'sentry/locale';
+import space from 'sentry/styles/space';
import {Crumb} from 'sentry/types/breadcrumbs';
import {Event} from 'sentry/types/event';
import getUrlPathname from 'sentry/utils/getUrlPathname';
+import createUrlToShare from 'sentry/utils/replays/createUrlToShare';
type Props = {
children: React.ReactNode;
@@ -25,8 +30,13 @@ type Props = {
};
function DetailLayout({children, event, orgId, crumbs}: Props) {
+ const {currentTime} = useReplayContext();
const title = event ? `${event.id} - Replays - ${orgId}` : `Replays - ${orgId}`;
+ const urlToShare = useMemo(() => {
+ return createUrlToShare(currentTime);
+ }, [currentTime]);
+
return (
<SentryDocumentTitle title={title}>
<React.Fragment>
@@ -49,7 +59,10 @@ function DetailLayout({children, event, orgId, crumbs}: Props) {
]}
/>
</Layout.HeaderContent>
- <FeedbackButtonWrapper>
+ <ButtonActionsWrapper>
+ <Clipboard hideUnsupported value={urlToShare}>
+ <Button icon={<IconLink />}>{t('Share')}</Button>
+ </Clipboard>
<FeatureFeedback
featureName="replay"
feedbackTypes={[
@@ -59,7 +72,7 @@ function DetailLayout({children, event, orgId, crumbs}: Props) {
'Other reason',
]}
/>
- </FeedbackButtonWrapper>
+ </ButtonActionsWrapper>
<React.Fragment>
<Layout.HeaderContent>
<EventHeader event={event} />
@@ -154,8 +167,11 @@ const BigNameUserBadge = styled(UserBadge)`
`;
// TODO(replay); This could make a lot of sense to put inside HeaderActions by default
-const FeedbackButtonWrapper = styled(Layout.HeaderActions)`
- align-items: end;
+const ButtonActionsWrapper = styled(Layout.HeaderActions)`
+ display: grid;
+ grid-template-columns: repeat(2, max-content);
+ justify-content: flex-end;
+ gap: ${space(1)};
`;
export default DetailLayout;
|
48af2f53af650998e0f265952b479136017a9438
|
2022-09-20 03:12:28
|
Jonas
|
feat(profiling): show update prompt if SDK updates are available (#37857)
| false
|
show update prompt if SDK updates are available (#37857)
|
feat
|
diff --git a/static/app/components/profiling/ProfilingOnboarding/profilingOnboardingModal.spec.tsx b/static/app/components/profiling/ProfilingOnboarding/profilingOnboardingModal.spec.tsx
index 4eca1167fde77d..f5d9bfa32d862b 100644
--- a/static/app/components/profiling/ProfilingOnboarding/profilingOnboardingModal.spec.tsx
+++ b/static/app/components/profiling/ProfilingOnboarding/profilingOnboardingModal.spec.tsx
@@ -19,49 +19,108 @@ function selectProject(project: Project) {
throw new Error(`Selected project requires a name, received ${project.name}`);
}
- userEvent.click(screen.getAllByRole('textbox')[0]!);
+ userEvent.click(screen.getAllByRole('textbox')[0]);
userEvent.click(screen.getByText(project.name));
}
describe('ProfilingOnboarding', function () {
beforeEach(() => {
+ // @ts-ignore no-console
+ // eslint-disable-next-line no-console
+ jest.spyOn(console, 'error').mockImplementation(jest.fn());
+ });
+ afterEach(() => {
+ MockApiClient.clearMockResponses();
ProjectStore.teardown();
+ // @ts-ignore no-console
+ // eslint-disable-next-line no-console
+ console.error.mockRestore();
});
it('renders default step', () => {
- render(<ProfilingOnboardingModal {...MockRenderModalProps} />);
+ const organization = TestStubs.Organization();
+ MockApiClient.addMockResponse({
+ url: `/organizations/${organization.slug}/sdk-updates/`,
+ body: [],
+ });
+
+ render(
+ <ProfilingOnboardingModal organization={organization} {...MockRenderModalProps} />
+ );
expect(screen.getByText(/Select a Project/i)).toBeInTheDocument();
});
it('goes to next step and previous step if project is supported', () => {
+ const organization = TestStubs.Organization();
ProjectStore.loadInitialData([
TestStubs.Project({name: 'iOS Project', platform: 'apple-ios'}),
]);
- render(<ProfilingOnboardingModal {...MockRenderModalProps} />);
+ MockApiClient.addMockResponse({
+ url: `/organizations/${organization.slug}/sdk-updates/`,
+ body: [],
+ });
+
+ render(
+ <ProfilingOnboardingModal organization={organization} {...MockRenderModalProps} />
+ );
selectProject(TestStubs.Project({name: 'iOS Project'}));
act(() => {
- userEvent.click(screen.getAllByText('Next')[0]!);
+ userEvent.click(screen.getAllByText('Next')[0]);
});
expect(screen.getByText(/Step 2 of 2/i)).toBeInTheDocument();
- // Previous step
act(() => {
- userEvent.click(screen.getAllByText('Back')[0]!);
+ userEvent.click(screen.getAllByText('Back')[0]);
});
expect(screen.getByText(/Select a Project/i)).toBeInTheDocument();
});
it('does not allow going to next step if project is unsupported', () => {
+ const organization = TestStubs.Organization();
ProjectStore.loadInitialData([
TestStubs.Project({name: 'javascript', platform: 'javascript'}),
]);
- render(<ProfilingOnboardingModal {...MockRenderModalProps} />);
- selectProject(TestStubs.Project({name: 'javascript'}));
- act(() => {
- userEvent.click(screen.getAllByText('Next')[0]!);
+ MockApiClient.addMockResponse({
+ url: `/organizations/${organization.slug}/sdk-updates/`,
+ body: [],
});
+
+ render(
+ <ProfilingOnboardingModal organization={organization} {...MockRenderModalProps} />
+ );
+ selectProject(TestStubs.Project({name: 'javascript'}));
+ userEvent.click(screen.getAllByText('Next')[0]);
+
expect(screen.getByRole('button', {name: /Next/i})).toBeDisabled();
});
+
+ it('shows sdk updates are required if version is lower than required', async () => {
+ const organization = TestStubs.Organization();
+ const project = TestStubs.Project({name: 'iOS Project', platform: 'apple-ios'});
+ ProjectStore.loadInitialData([project]);
+
+ MockApiClient.addMockResponse({
+ url: `/organizations/${organization.slug}/sdk-updates/`,
+ body: [
+ {
+ projectId: project.id,
+ sdkName: 'sentry ios',
+ sdkVersion: '6.0.0',
+ suggestions: [],
+ },
+ ],
+ });
+
+ render(
+ <ProfilingOnboardingModal organization={organization} {...MockRenderModalProps} />
+ );
+
+ selectProject(project);
+
+ expect(
+ await screen.findByText(/Update your projects SDK version/)
+ ).toBeInTheDocument();
+ });
});
diff --git a/static/app/components/profiling/ProfilingOnboarding/profilingOnboardingModal.tsx b/static/app/components/profiling/ProfilingOnboarding/profilingOnboardingModal.tsx
index 1d4b5351d1618e..d9209bfa6843f6 100644
--- a/static/app/components/profiling/ProfilingOnboarding/profilingOnboardingModal.tsx
+++ b/static/app/components/profiling/ProfilingOnboarding/profilingOnboardingModal.tsx
@@ -12,8 +12,12 @@ import Tag from 'sentry/components/tag';
import {IconOpen} from 'sentry/icons';
import {t, tct} from 'sentry/locale';
import space from 'sentry/styles/space';
-import {Project} from 'sentry/types/project';
+import {Organization} from 'sentry/types';
+import {RequestState} from 'sentry/types/core';
+import {Project, ProjectSdkUpdates} from 'sentry/types/project';
+import {semverCompare} from 'sentry/utils/profiling/units/versions';
import useProjects from 'sentry/utils/useProjects';
+import {useProjectSdkUpdates} from 'sentry/utils/useProjectSdkUpdates';
// This is just a doubly linked list of steps
interface OnboardingStep {
@@ -48,7 +52,11 @@ function useOnboardingRouter(initialStep: OnboardingStep): OnboardingRouterState
// The wrapper component for all of the onboarding steps. Keeps track of the current step
// and all state. This ensures that moving from step to step does not require users to redo their actions
// and each step can just re-initialize with the values that the user has already selected.
-export function ProfilingOnboardingModal(props: ModalRenderProps) {
+
+interface ProfilingOnboardingModalProps extends ModalRenderProps {
+ organization: Organization;
+}
+export function ProfilingOnboardingModal(props: ProfilingOnboardingModalProps) {
const [state, toStep] = useOnboardingRouter({
previous: null,
current: SelectProjectStep,
@@ -111,6 +119,7 @@ function splitProjectsByProfilingSupport(projects: Project[]): {
// We proxy the modal props to each individaul modal component
// so that each can build their own modal and they can remain independent.
interface OnboardingStepProps extends ModalRenderProps {
+ organization: Organization;
project: Project | null;
setProject: React.Dispatch<React.SetStateAction<Project | null>>;
step: OnboardingStep;
@@ -126,6 +135,7 @@ function SelectProjectStep({
step,
project,
setProject,
+ organization,
}: OnboardingStepProps) {
const {projects} = useProjects();
@@ -169,6 +179,8 @@ function SelectProjectStep({
];
}, [projects]);
+ const sdkUpdates = useProjectSdkUpdates({organization, projectId: project?.id ?? null});
+
return (
<ModalBody>
<ModalHeader>
@@ -189,8 +201,12 @@ function SelectProjectStep({
/>
</div>
</li>
- {project?.platform === 'android' ? <AndroidInstallSteps /> : null}
- {project?.platform === 'apple-ios' ? <IOSInstallSteps /> : null}
+ {project?.platform === 'android' ? (
+ <AndroidInstallSteps sdkUpdates={sdkUpdates} project={project} />
+ ) : null}
+ {project?.platform === 'apple-ios' ? (
+ <IOSInstallSteps sdkUpdates={sdkUpdates} project={project} />
+ ) : null}
</StyledList>
<ModalFooter>
<ModalActions>
@@ -230,17 +246,79 @@ function SetupPerformanceMonitoringStep({href}: {href: string}) {
);
}
-function AndroidInstallSteps() {
+interface ProjectSdkUpdateProps {
+ minSdkVersion: string;
+ project: Project;
+ sdkUpdates: RequestState<ProjectSdkUpdates | null>;
+}
+function ProjectSdkUpdate(props: ProjectSdkUpdateProps) {
+ if (props.sdkUpdates.type !== 'resolved') {
+ return <div>{t('Verifying Sentry SDK')}</div>;
+ }
+
return (
<Fragment>
- <li>
- <StepTitle>{t('Update your projects SDK version')}</StepTitle>
- <p>
+ <SDKUpdatesContainer>
+ <SdkUpdatesPlatformIcon platform={props.project.platform ?? 'unknown'} />
+ <span>{props.project.name}</span>
+ </SDKUpdatesContainer>
+ {props.sdkUpdates.data === null ? (
+ <SdkUpdatesText>
+ {t('This project is using the latest SDK version.')}
+ </SdkUpdatesText>
+ ) : (
+ <SdkUpdatesText>
{t(
- 'Make sure your SDKs are upgraded to at least version 6.0.0 (sentry-android).'
+ 'For profiling to function, we requires you to update your Sentry SDK to version %s or higher.',
+ props.minSdkVersion
)}
- </p>
- </li>
+ </SdkUpdatesText>
+ )}
+ </Fragment>
+ );
+}
+
+const SdkUpdatesText = styled('p')`
+ margin-top: ${space(1.5)};
+ padding-left: ${space(4)};
+`;
+
+// doesnt use space because it's just off by 2px all the time
+const SdkUpdatesPlatformIcon = styled(PlatformIcon)`
+ margin-right: 10px;
+`;
+
+const SDKUpdatesContainer = styled('div')`
+ display: flex;
+ align-items: center;
+ margin-top: ${space(1.5)};
+ font-size: ${p => p.theme.fontSizeLarge};
+`;
+
+function AndroidInstallSteps({
+ project,
+ sdkUpdates,
+}: {
+ project: Project;
+ sdkUpdates: RequestState<ProjectSdkUpdates | null>;
+}) {
+ const requiresSdkUpdates =
+ sdkUpdates.type === 'resolved' && sdkUpdates.data?.sdkVersion
+ ? semverCompare(sdkUpdates.data.sdkVersion, '6.0.0') < 0
+ : false;
+
+ return (
+ <Fragment>
+ {requiresSdkUpdates ? (
+ <li>
+ <StepTitle>{t('Update your projects SDK version')}</StepTitle>
+ <ProjectSdkUpdate
+ minSdkVersion="6.0.0 (sentry-android)"
+ project={project}
+ sdkUpdates={sdkUpdates}
+ />
+ </li>
+ ) : null}
<li>
<SetupPerformanceMonitoringStep href="https://docs.sentry.io/platforms/android/performance/" />
</li>
@@ -258,17 +336,30 @@ function AndroidInstallSteps() {
);
}
-function IOSInstallSteps() {
+function IOSInstallSteps({
+ project,
+ sdkUpdates,
+}: {
+ project: Project;
+ sdkUpdates: RequestState<ProjectSdkUpdates | null>;
+}) {
+ const requiresSdkUpdates =
+ sdkUpdates.type === 'resolved' && sdkUpdates.data?.sdkVersion
+ ? semverCompare(sdkUpdates.data.sdkVersion, '7.23.0') < 0
+ : false;
+
return (
<Fragment>
- <li>
- <StepTitle>{t('Update your projects SDK version')}</StepTitle>
- <p>
- {t(
- 'Make sure your SDKs are upgraded to at least version 7.23.0 (sentry-cocoa).'
- )}
- </p>
- </li>
+ {requiresSdkUpdates ? (
+ <li>
+ <StepTitle>{t('Update your projects SDK version')}</StepTitle>
+ <ProjectSdkUpdate
+ minSdkVersion="7.23.0 (sentry-cocoa)"
+ project={project}
+ sdkUpdates={sdkUpdates}
+ />
+ </li>
+ ) : null}
<li>
<SetupPerformanceMonitoringStep href="https://docs.sentry.io/platforms/apple/guides/ios/performance/" />
</li>
diff --git a/static/app/utils/profiling/units/versions.spec.tsx b/static/app/utils/profiling/units/versions.spec.tsx
new file mode 100644
index 00000000000000..30f5868cf768d6
--- /dev/null
+++ b/static/app/utils/profiling/units/versions.spec.tsx
@@ -0,0 +1,38 @@
+/* Taken from https://gist.github.com/iwill/a83038623ba4fef6abb9efca87ae9ccb
+ * returns -1 for smaller, 0 for equals, and 1 for greater than
+ */
+import {semverCompare} from './versions';
+
+function testVersion(v1: string, operator: '<' | '>' | '=', v2: string) {
+ const result = semverCompare(v1, v2);
+ if (operator === '<') {
+ expect(result).toBe(-1);
+ }
+ if (operator === '>') {
+ expect(result).toBe(1);
+ }
+ if (operator === '=') {
+ expect(result).toBe(0);
+ }
+}
+describe('semverCompar', () => {
+ it('compares versions', () => {
+ // 1.0.0 < 2.0.0 < 2.1.0 < 2.1.1
+ testVersion('1.0.0', '=', '1.0.0');
+ testVersion('1.0.0', '<', '2.0.0');
+ testVersion('2.0.0', '<', '2.1.0');
+ testVersion('2.1.0', '<', '2.1.1');
+
+ // 1.0.0-alpha < 1.0.0
+ testVersion('1.0.0-alpha', '<', '1.0.0');
+
+ // 1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-alpha.beta < 1.0.0-beta < 1.0.0-beta.2 < 1.0.0-beta.11 < 1.0.0-rc.1 < 1.0.0
+ testVersion('1.0.0-alpha', '<', '1.0.0-alpha.1');
+ testVersion('1.0.0-alpha.1', '<', '1.0.0-alpha.beta');
+ testVersion('1.0.0-alpha.beta', '<', '1.0.0-beta');
+ testVersion('1.0.0-beta', '<', '1.0.0-beta.2');
+ testVersion('1.0.0-beta.2', '<', '1.0.0-beta.11');
+ testVersion('1.0.0-beta.11', '<', '1.0.0-rc.1');
+ testVersion('1.0.0-rc.1', '<', '1.0.0');
+ });
+});
diff --git a/static/app/utils/profiling/units/versions.ts b/static/app/utils/profiling/units/versions.ts
new file mode 100644
index 00000000000000..60d3ca20ae17e2
--- /dev/null
+++ b/static/app/utils/profiling/units/versions.ts
@@ -0,0 +1,21 @@
+/**
+ * Semantic Versioning Comparing
+ * #see https://semver.org/
+ * #see https://stackoverflow.com/a/65687141/456536
+ * #see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#options
+ * Taken from https://gist.github.com/iwill/a83038623ba4fef6abb9efca87ae9ccb
+ * returns -1 for smaller, 0 for equals, and 1 for greater than
+ */
+export function semverCompare(a: string, b: string): number {
+ if (a.startsWith(b + '-')) {
+ return -1;
+ }
+ if (b.startsWith(a + '-')) {
+ return 1;
+ }
+ return a.localeCompare(b, undefined, {
+ numeric: true,
+ sensitivity: 'case',
+ caseFirst: 'upper',
+ });
+}
diff --git a/static/app/utils/useProjectSdkUpdates.tsx b/static/app/utils/useProjectSdkUpdates.tsx
new file mode 100644
index 00000000000000..3d0738a637d357
--- /dev/null
+++ b/static/app/utils/useProjectSdkUpdates.tsx
@@ -0,0 +1,80 @@
+import {useEffect, useMemo, useState} from 'react';
+
+import {Client} from 'sentry/api';
+import {RequestState} from 'sentry/types';
+
+import {Organization} from '../types/organization';
+import {Project, ProjectSdkUpdates} from '../types/project';
+
+import useApi from './useApi';
+
+function loadSdkUpdates(api: Client, orgSlug: string): Promise<ProjectSdkUpdates[]> {
+ return api.requestPromise(`/organizations/${orgSlug}/sdk-updates/`);
+}
+
+interface UseProjectSdkOptions {
+ organization: Organization;
+ projectId: Project['id'] | null;
+}
+
+export function useProjectSdkUpdates(
+ options: UseProjectSdkOptions
+): RequestState<ProjectSdkUpdates | null> {
+ const api = useApi();
+ const [state, setState] = useState<RequestState<ProjectSdkUpdates[] | null>>({
+ type: 'initial',
+ });
+
+ useEffect(() => {
+ let unmounted = false;
+
+ loadSdkUpdates(api, options.organization.slug)
+ .then(data => {
+ if (unmounted) {
+ return;
+ }
+
+ setState({
+ type: 'resolved',
+ data,
+ });
+ })
+ .catch(e => {
+ if (unmounted) {
+ return;
+ }
+ setState({
+ type: 'errored',
+ error: e,
+ });
+ });
+
+ return () => {
+ unmounted = true;
+ };
+ }, [api, options.organization.slug]);
+
+ const stateForProject = useMemo((): RequestState<ProjectSdkUpdates | null> => {
+ if (!options.projectId) {
+ return {
+ ...state,
+ type: 'resolved',
+ data: null,
+ };
+ }
+ if (state.type === 'resolved') {
+ return {
+ ...state,
+ type: 'resolved',
+ data:
+ state.type === 'resolved' && state.data
+ ? state.data.find(sdk => sdk.projectId === options.projectId) ?? null
+ : null,
+ };
+ }
+
+ return state;
+ }, [state, options.projectId]);
+
+ return stateForProject;
+}
diff --git a/static/app/views/profiling/content.tsx b/static/app/views/profiling/content.tsx
index a0a37893b1cfea..f81790de25da84 100644
--- a/static/app/views/profiling/content.tsx
+++ b/static/app/views/profiling/content.tsx
@@ -112,9 +112,9 @@ function ProfilingContent({location, router}: ProfilingContentProps) {
// Open the modal on demand
const onSetupProfilingClick = useCallback(() => {
openModal(props => {
- return <ProfilingOnboardingModal {...props} />;
+ return <ProfilingOnboardingModal {...props} organization={organization} />;
});
- }, []);
+ }, [organization]);
const shouldShowProfilingOnboardingPanel = useMemo((): boolean => {
if (transactions.type !== 'resolved') {
|
d3bb3dab45ae4afbb618f054992045fe5afcf122
|
2020-03-05 07:39:37
|
Lyn Nagara
|
test: Fix eventstream test (#17470)
| false
|
Fix eventstream test (#17470)
|
test
|
diff --git a/tests/snuba/eventstream/test_eventstream.py b/tests/snuba/eventstream/test_eventstream.py
index 23755906fd6bea..22be0037c07aad 100644
--- a/tests/snuba/eventstream/test_eventstream.py
+++ b/tests/snuba/eventstream/test_eventstream.py
@@ -55,16 +55,6 @@ def __produce_event(self, *insert_args, **insert_kwargs):
def test(self, mock_eventstream_insert):
now = datetime.utcnow()
- def _get_event_count():
- return snuba.query(
- start=now - timedelta(days=1),
- end=now + timedelta(days=1),
- groupby=["project_id"],
- filter_keys={"project_id": [self.project.id]},
- ).get(self.project.id, 0)
-
- assert _get_event_count() == 0
-
event = self.__build_event(now)
# verify eventstream was called by EventManager
@@ -82,7 +72,12 @@ def _get_event_count():
}
self.__produce_event(*insert_args, **insert_kwargs)
- assert _get_event_count() == 1
+ assert snuba.query(
+ start=now - timedelta(days=1),
+ end=now + timedelta(days=1),
+ groupby=["project_id"],
+ filter_keys={"project_id": [self.project.id]},
+ ).get(self.project.id, 0) == 1
@patch("sentry.eventstream.insert")
def test_issueless(self, mock_eventstream_insert):
|
7a0ab1d7c6d52374a2467f6e88a18e17753bdebd
|
2024-07-04 02:14:19
|
edwardgou-sentry
|
chore(insights): removes unused webvitals flags (#73756)
| false
|
removes unused webvitals flags (#73756)
|
chore
|
diff --git a/src/sentry/features/temporary.py b/src/sentry/features/temporary.py
index 276e87a2b8ed2d..6e39d51e9a0cdc 100644
--- a/src/sentry/features/temporary.py
+++ b/src/sentry/features/temporary.py
@@ -423,16 +423,6 @@ def register_temporary_features(manager: FeatureManager):
manager.add("organizations:starfish-browser-resource-module-image-view", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
# Enables the resource module ui
manager.add("organizations:starfish-browser-resource-module-ui", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
- # Enable browser starfish webvitals module view
- manager.add("organizations:starfish-browser-webvitals", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
- # Enable browser starfish webvitals module pageoverview v2 view
- manager.add("organizations:starfish-browser-webvitals-pageoverview-v2", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
- # Enable INP in the browser starfish webvitals module
- manager.add("organizations:starfish-browser-webvitals-replace-fid-with-inp", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
- # Update Web Vitals UI to display aggregate web vital values as avg instead of p75
- manager.add("organizations:performance-webvitals-avg", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
- # Enable browser starfish webvitals module to use backend provided performance scores
- manager.add("organizations:starfish-browser-webvitals-use-backend-scores", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
# Enable mobile starfish app start module view
manager.add("organizations:starfish-mobile-appstart", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
# Enable mobile starfish ui module view
|
4a2b335f156b35d7bcd0017a3f4c65fcf5464d33
|
2022-03-23 04:05:35
|
Evan Purkhiser
|
chore: Remove unused .mailmap file (#32852)
| false
|
Remove unused .mailmap file (#32852)
|
chore
|
diff --git a/.mailmap b/.mailmap
deleted file mode 100644
index b4d851488302ae..00000000000000
--- a/.mailmap
+++ /dev/null
@@ -1 +0,0 @@
-Matt Robenolt <[email protected]> Matt Robenolt <[email protected]>
|
50e0226833e08244233f731f1f05eaeadbe9f7ac
|
2018-02-16 01:00:56
|
Billy Vong
|
fix(ui): Fix PluginConfig calling disable plugin multiple times (#7215)
| false
|
Fix PluginConfig calling disable plugin multiple times (#7215)
|
fix
|
diff --git a/src/sentry/static/sentry/app/components/pluginConfig.jsx b/src/sentry/static/sentry/app/components/pluginConfig.jsx
index 59512d7d5ca637..204c50d800f4c1 100644
--- a/src/sentry/static/sentry/app/components/pluginConfig.jsx
+++ b/src/sentry/static/sentry/app/components/pluginConfig.jsx
@@ -4,7 +4,6 @@ import React from 'react';
import _ from 'lodash';
import createReactClass from 'create-react-class';
-import {disablePlugin} from '../actionCreators/plugins';
import {t} from '../locale';
import ApiMixin from '../mixins/apiMixin';
import Button from './buttons/button';
@@ -75,9 +74,6 @@ const PluginConfig = createReactClass({
},
disablePlugin() {
- let {organization, project, data} = this.props;
- disablePlugin({projectId: project.slug, orgId: organization.slug, pluginId: data.id});
-
this.props.onDisablePlugin(this.props.data);
},
diff --git a/src/sentry/static/sentry/app/components/pluginList.jsx b/src/sentry/static/sentry/app/components/pluginList.jsx
index 1c2d426feb1f2c..3573c2a43a1589 100644
--- a/src/sentry/static/sentry/app/components/pluginList.jsx
+++ b/src/sentry/static/sentry/app/components/pluginList.jsx
@@ -1,35 +1,26 @@
import PropTypes from 'prop-types';
import React from 'react';
-import createReactClass from 'create-react-class';
import {enablePlugin, disablePlugin} from '../actionCreators/plugins';
-import ApiMixin from '../mixins/apiMixin';
import InactivePlugins from './inactivePlugins';
import PluginConfig from './pluginConfig';
import {t} from '../locale';
-
-export default createReactClass({
- displayName: 'PluginList',
-
- propTypes: {
+export default class PluginList extends React.Component {
+ static propTypes = {
organization: PropTypes.object.isRequired,
project: PropTypes.object.isRequired,
pluginList: PropTypes.array.isRequired,
onDisablePlugin: PropTypes.func.isRequired,
onEnablePlugin: PropTypes.func.isRequired,
- },
-
- mixins: [ApiMixin],
+ };
- getDefaultProps() {
- return {
- onDisablePlugin: () => {},
- onEnablePlugin: () => {},
- };
- },
+ static defaultProps = {
+ onDisablePlugin: () => {},
+ onEnablePlugin: () => {},
+ };
- handleEnablePlugin(plugin) {
+ handleEnablePlugin = plugin => {
let {organization, project} = this.props;
enablePlugin({
projectId: project.slug,
@@ -38,9 +29,9 @@ export default createReactClass({
});
this.props.onEnablePlugin(plugin);
- },
+ };
- handleDisablePlugin(plugin) {
+ handleDisablePlugin = plugin => {
let {organization, project} = this.props;
disablePlugin({
projectId: project.slug,
@@ -49,7 +40,7 @@ export default createReactClass({
});
this.props.onDisablePlugin(plugin);
- },
+ };
render() {
let {organization, pluginList, project} = this.props;
@@ -86,5 +77,5 @@ export default createReactClass({
/>
</div>
);
- },
-});
+ }
+}
|
64c4d9fbaccb994fc5e01f4525b5f8c1cd101615
|
2024-04-26 23:35:47
|
Colleen O'Rourke
|
ref(rules): Pull out RuleProcessor methods to be reusable (#69739)
| false
|
Pull out RuleProcessor methods to be reusable (#69739)
|
ref
|
diff --git a/src/sentry/api/endpoints/project_rule_actions.py b/src/sentry/api/endpoints/project_rule_actions.py
index 15049bec8035e7..c38dc1825a40eb 100644
--- a/src/sentry/api/endpoints/project_rule_actions.py
+++ b/src/sentry/api/endpoints/project_rule_actions.py
@@ -8,7 +8,7 @@
from sentry.api.bases import ProjectAlertRulePermission, ProjectEndpoint
from sentry.api.serializers.rest_framework import RuleActionSerializer
from sentry.models.rule import Rule
-from sentry.rules.processing.processor import RuleProcessor
+from sentry.rules.processing.processor import activate_downstream_actions
from sentry.utils.safe import safe_execute
from sentry.utils.samples import create_sample_event
@@ -60,10 +60,7 @@ def post(self, request: Request, project) -> Response:
project, platform=project.platform, default="javascript", tagged=True
)
- rp = RuleProcessor(test_event, False, False, False, False)
- rp.activate_downstream_actions(rule)
-
- for callback, futures in rp.grouped_futures.values():
+ for callback, futures in activate_downstream_actions(rule, test_event).values():
safe_execute(callback, test_event, futures, _with_transaction=False)
return Response()
diff --git a/src/sentry/rules/processing/processor.py b/src/sentry/rules/processing/processor.py
index 4b737d70d13ca2..546423104e64ff 100644
--- a/src/sentry/rules/processing/processor.py
+++ b/src/sentry/rules/processing/processor.py
@@ -13,6 +13,7 @@
from sentry import analytics
from sentry.eventstore.models import GroupEvent
from sentry.models.environment import Environment
+from sentry.models.group import Group
from sentry.models.grouprulestatus import GroupRuleStatus
from sentry.models.rule import Rule
from sentry.models.rulefirehistory import RuleFireHistory
@@ -75,6 +76,104 @@ def split_conditions_and_filters(rule_condition_list):
return condition_list, filter_list
+def build_rule_status_cache_key(rule_id: int, group_id: int) -> str:
+ return "grouprulestatus:1:%s" % hash_values([group_id, rule_id])
+
+
+def bulk_get_rule_status(rules: Sequence[Rule], group: Group) -> Mapping[int, GroupRuleStatus]:
+ keys = [build_rule_status_cache_key(rule.id, group.id) for rule in rules]
+ cache_results: Mapping[str, GroupRuleStatus] = cache.get_many(keys)
+ missing_rule_ids: set[int] = set()
+ rule_statuses: MutableMapping[int, GroupRuleStatus] = {}
+ for key, rule in zip(keys, rules):
+ rule_status = cache_results.get(key)
+ if not rule_status:
+ missing_rule_ids.add(rule.id)
+ else:
+ rule_statuses[rule.id] = rule_status
+
+ if missing_rule_ids:
+ # If not cached, attempt to fetch status from the database
+ statuses = GroupRuleStatus.objects.filter(group=group, rule_id__in=missing_rule_ids)
+ to_cache: list[GroupRuleStatus] = list()
+ for status in statuses:
+ rule_statuses[status.rule_id] = status
+ missing_rule_ids.remove(status.rule_id)
+ to_cache.append(status)
+
+ # We might need to create some statuses if they don't already exist
+ if missing_rule_ids:
+ # We use `ignore_conflicts=True` here to avoid race conditions where the statuses
+ # might be created between when we queried above and attempt to create the rows now.
+ GroupRuleStatus.objects.bulk_create(
+ [
+ GroupRuleStatus(rule_id=rule_id, group=group, project=group.project)
+ for rule_id in missing_rule_ids
+ ],
+ ignore_conflicts=True,
+ )
+ # Using `ignore_conflicts=True` prevents the pk from being set on the model
+ # instances. Re-query the database to fetch the rows, they should all exist at this
+ # point.
+ statuses = GroupRuleStatus.objects.filter(group=group, rule_id__in=missing_rule_ids)
+ for status in statuses:
+ rule_statuses[status.rule_id] = status
+ missing_rule_ids.remove(status.rule_id)
+ to_cache.append(status)
+
+ if missing_rule_ids:
+ # Shouldn't happen, but log just in case
+ logger.error(
+ "Failed to fetch some GroupRuleStatuses in RuleProcessor",
+ extra={"missing_rule_ids": missing_rule_ids, "group_id": group.id},
+ )
+ if to_cache:
+ cache.set_many(
+ {build_rule_status_cache_key(item.rule_id, group.id): item for item in to_cache}
+ )
+
+ return rule_statuses
+
+
+def activate_downstream_actions(
+ rule: Rule,
+ event: GroupEvent,
+ notification_uuid: str | None = None,
+ rule_fire_history: RuleFireHistory | None = None,
+) -> MutableMapping[
+ str, tuple[Callable[[GroupEvent, Sequence[RuleFuture]], None], list[RuleFuture]]
+]:
+ grouped_futures: MutableMapping[
+ str, tuple[Callable[[GroupEvent, Sequence[RuleFuture]], None], list[RuleFuture]]
+ ] = {}
+
+ for action in rule.data.get("actions", ()):
+ action_inst = instantiate_action(rule, action, rule_fire_history)
+ if not action_inst:
+ continue
+
+ results = safe_execute(
+ action_inst.after,
+ event=event,
+ _with_transaction=False,
+ notification_uuid=notification_uuid,
+ )
+ if results is None:
+ logger.warning("Action %s did not return any futures", action["id"])
+ continue
+
+ for future in results:
+ key = future.key if future.key is not None else future.callback
+ rule_future = RuleFuture(rule=rule, kwargs=future.kwargs)
+
+ if key not in grouped_futures:
+ grouped_futures[key] = (future.callback, [rule_future])
+ else:
+ grouped_futures[key][1].append(rule_future)
+
+ return grouped_futures
+
+
class RuleProcessor:
def __init__(
self,
@@ -104,67 +203,6 @@ def get_rules(self) -> Sequence[Rule]:
rules_: Sequence[Rule] = Rule.get_for_project(self.project.id)
return rules_
- def _build_rule_status_cache_key(self, rule_id: int) -> str:
- return "grouprulestatus:1:%s" % hash_values([self.group.id, rule_id])
-
- def bulk_get_rule_status(self, rules: Sequence[Rule]) -> Mapping[int, GroupRuleStatus]:
- keys = [self._build_rule_status_cache_key(rule.id) for rule in rules]
- cache_results: Mapping[str, GroupRuleStatus] = cache.get_many(keys)
- missing_rule_ids: set[int] = set()
- rule_statuses: MutableMapping[int, GroupRuleStatus] = {}
- for key, rule in zip(keys, rules):
- rule_status = cache_results.get(key)
- if not rule_status:
- missing_rule_ids.add(rule.id)
- else:
- rule_statuses[rule.id] = rule_status
-
- if missing_rule_ids:
- # If not cached, attempt to fetch status from the database
- statuses = GroupRuleStatus.objects.filter(
- group=self.group, rule_id__in=missing_rule_ids
- )
- to_cache: list[GroupRuleStatus] = list()
- for status in statuses:
- rule_statuses[status.rule_id] = status
- missing_rule_ids.remove(status.rule_id)
- to_cache.append(status)
-
- # We might need to create some statuses if they don't already exist
- if missing_rule_ids:
- # We use `ignore_conflicts=True` here to avoid race conditions where the statuses
- # might be created between when we queried above and attempt to create the rows now.
- GroupRuleStatus.objects.bulk_create(
- [
- GroupRuleStatus(rule_id=rule_id, group=self.group, project=self.project)
- for rule_id in missing_rule_ids
- ],
- ignore_conflicts=True,
- )
- # Using `ignore_conflicts=True` prevents the pk from being set on the model
- # instances. Re-query the database to fetch the rows, they should all exist at this
- # point.
- statuses = GroupRuleStatus.objects.filter(
- group=self.group, rule_id__in=missing_rule_ids
- )
- for status in statuses:
- rule_statuses[status.rule_id] = status
- missing_rule_ids.remove(status.rule_id)
- to_cache.append(status)
-
- if missing_rule_ids:
- # Shouldn't happen, but log just in case
- logger.error(
- "Failed to fetch some GroupRuleStatuses in RuleProcessor",
- extra={"missing_rule_ids": missing_rule_ids, "group_id": self.group.id},
- )
- if to_cache:
- cache.set_many(
- {self._build_rule_status_cache_key(item.rule_id): item for item in to_cache}
- )
-
- return rule_statuses
-
def condition_matches(
self,
condition: MutableMapping[str, Any],
@@ -279,37 +317,14 @@ def apply_rule(self, rule: Rule, status: GroupRuleStatus) -> None:
notification_uuid = str(uuid.uuid4())
rule_fire_history = history.record(rule, self.group, self.event.event_id, notification_uuid)
- self.activate_downstream_actions(rule, notification_uuid, rule_fire_history)
-
- def activate_downstream_actions(
- self,
- rule: Rule,
- notification_uuid: str | None = None,
- rule_fire_history: RuleFireHistory | None = None,
- ) -> None:
- for action in rule.data.get("actions", ()):
- action_inst = instantiate_action(rule, action, rule_fire_history)
- if not action_inst:
- continue
-
- results = safe_execute(
- action_inst.after,
- event=self.event,
- _with_transaction=False,
- notification_uuid=notification_uuid,
- )
- if results is None:
- logger.warning("Action %s did not return any futures", action["id"])
- continue
-
- for future in results:
- key = future.key if future.key is not None else future.callback
- rule_future = RuleFuture(rule=rule, kwargs=future.kwargs)
+ grouped_futures = activate_downstream_actions(
+ rule, self.event, notification_uuid, rule_fire_history
+ )
- if key not in self.grouped_futures:
- self.grouped_futures[key] = (future.callback, [rule_future])
- else:
- self.grouped_futures[key][1].append(rule_future)
+ if not self.grouped_futures:
+ self.grouped_futures = grouped_futures
+ else:
+ self.grouped_futures.update(grouped_futures)
def apply(
self,
@@ -323,7 +338,7 @@ def apply(
snoozed_rules = RuleSnooze.objects.filter(rule__in=rules, user_id=None).values_list(
"rule", flat=True
)
- rule_statuses = self.bulk_get_rule_status(rules)
+ rule_statuses = bulk_get_rule_status(rules, self.group)
for rule in rules:
if rule.id not in snoozed_rules:
self.apply_rule(rule, rule_statuses[rule.id])
diff --git a/tests/sentry/rules/processing/test_processor.py b/tests/sentry/rules/processing/test_processor.py
index e0c779c57d2880..0908a39894538e 100644
--- a/tests/sentry/rules/processing/test_processor.py
+++ b/tests/sentry/rules/processing/test_processor.py
@@ -555,7 +555,7 @@ def test_last_active_too_recent(self):
)
with mock.patch(
- "sentry.rules.processing.processor.RuleProcessor.bulk_get_rule_status",
+ "sentry.rules.processing.processor.bulk_get_rule_status",
return_value={self.rule.id: grs},
):
results = list(rp.apply())
|
028e402dcb055c6099e55904200a05a9b86be02a
|
2024-07-16 22:47:05
|
Tony Xiao
|
fix(profiling): Cast profile chunk timestamps to DateTime64 (#74348)
| false
|
Cast profile chunk timestamps to DateTime64 (#74348)
|
fix
|
diff --git a/src/sentry/profiles/profile_chunks.py b/src/sentry/profiles/profile_chunks.py
index 65e3e7cf04f8e1..a89e423e0af246 100644
--- a/src/sentry/profiles/profile_chunks.py
+++ b/src/sentry/profiles/profile_chunks.py
@@ -1,4 +1,6 @@
-from snuba_sdk import Column, Condition, Direction, Op, OrderBy, Query, Request, Storage
+from datetime import datetime
+
+from snuba_sdk import Column, Condition, Direction, Function, Op, OrderBy, Query, Request, Storage
from sentry import options
from sentry.search.events.types import ParamsType
@@ -20,8 +22,16 @@ def get_chunk_ids(
Column("chunk_id"),
],
where=[
- Condition(Column("end_timestamp"), Op.GTE, params.get("start")),
- Condition(Column("start_timestamp"), Op.LT, params.get("end")),
+ Condition(
+ Column("end_timestamp"),
+ Op.GTE,
+ resolve_datetime64(params.get("start")),
+ ),
+ Condition(
+ Column("start_timestamp"),
+ Op.LT,
+ resolve_datetime64(params.get("end")),
+ ),
Condition(Column("project_id"), Op.EQ, project_id),
Condition(Column("profiler_id"), Op.EQ, profiler_id),
],
@@ -44,3 +54,23 @@ def get_chunk_ids(
)
return [row["chunk_id"] for row in result["data"]]
+
+
+def resolve_datetime64(value: datetime | None, precision: int = 6) -> Function | None:
+ # This is normally handled by the snuba-sdk but it assumes that the underlying
+ # table uses DateTime. Because we use DateTime64(6) as the underlying column,
+ # we need to cast to the same type or we risk truncating the timestamp which
+ # can lead to subtle errors.
+
+ if value is None:
+ return None
+
+ if isinstance(value, datetime) and value.tzinfo is not None:
+ # This is adapted from snuba-sdk
+ # See https://github.com/getsentry/snuba-sdk/blob/2f7f014920b4f527a87f18c05b6aa818212bec6e/snuba_sdk/visitors.py#L168-L172
+ delta = value.utcoffset()
+ assert delta is not None
+ value -= delta
+ value.replace(tzinfo=None)
+
+ return Function("toDateTime64", [value.isoformat(), precision])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.