/
dom_index.py
430 lines (356 loc) · 13.9 KB
/
dom_index.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
from __future__ import annotations
import logging
import random
import time
import uuid
from collections.abc import Generator
from hashlib import md5
from typing import Any, Literal, TypedDict, cast
from sentry import features
from sentry.conf.types.kafka_definition import Topic
from sentry.models.project import Project
from sentry.replays.usecases.ingest.events import SentryEvent
from sentry.replays.usecases.ingest.issue_creation import (
report_rage_click_issue,
report_rage_click_issue_with_replay_event,
)
from sentry.utils import json, kafka_config, metrics
from sentry.utils.pubsub import KafkaPublisher
logger = logging.getLogger("sentry.replays")
EVENT_LIMIT = 20
replay_publisher: KafkaPublisher | None = None
ReplayActionsEventPayloadClick = TypedDict(
"ReplayActionsEventPayloadClick",
{
"alt": str,
"aria_label": str,
"class": list[str],
"event_hash": str,
"id": str,
"node_id": int,
"component_name": str,
"role": str,
"tag": str,
"testid": str,
"text": str,
"timestamp": int,
"title": str,
"is_dead": int,
"is_rage": int,
},
)
class ReplayActionsEventPayload(TypedDict):
clicks: list[ReplayActionsEventPayloadClick]
replay_id: str
type: Literal["replay_actions"]
class ReplayActionsEvent(TypedDict):
payload: list[int]
project_id: int
replay_id: str
retention_days: int
start_time: float
type: Literal["replay_event"]
def parse_and_emit_replay_actions(
project_id: int,
replay_id: str,
retention_days: int,
segment_data: list[dict[str, Any]],
replay_event: dict[str, Any] | None,
) -> None:
with metrics.timer("replays.usecases.ingest.dom_index.parse_and_emit_replay_actions"):
message = parse_replay_actions(
project_id, replay_id, retention_days, segment_data, replay_event
)
if message is not None:
emit_replay_actions(message)
def emit_replay_actions(action: ReplayActionsEvent) -> None:
publisher = _initialize_publisher()
publisher.publish("ingest-replay-events", json.dumps(action))
def parse_replay_actions(
project_id: int,
replay_id: str,
retention_days: int,
segment_data: list[dict[str, Any]],
replay_event: dict[str, Any] | None,
) -> ReplayActionsEvent | None:
"""Parse RRWeb payload to ReplayActionsEvent."""
actions = get_user_actions(project_id, replay_id, segment_data, replay_event)
if len(actions) == 0:
return None
payload = create_replay_actions_payload(replay_id, actions)
return create_replay_actions_event(replay_id, project_id, retention_days, payload)
def create_replay_actions_event(
replay_id: str,
project_id: int,
retention_days: int,
payload: ReplayActionsEventPayload,
) -> ReplayActionsEvent:
return {
"type": "replay_event",
"start_time": time.time(),
"replay_id": replay_id,
"project_id": project_id,
"retention_days": retention_days,
"payload": list(json.dumps(payload).encode()),
}
def create_replay_actions_payload(
replay_id: str,
clicks: list[ReplayActionsEventPayloadClick],
) -> ReplayActionsEventPayload:
return {
"type": "replay_actions",
"replay_id": replay_id,
"clicks": clicks,
}
def log_canvas_size(
org_id: int,
project_id: int,
replay_id: str,
events: list[dict[str, Any]],
) -> None:
for event in events:
if event.get("type") == 3 and event.get("data", {}).get("source") == 9:
logger.info(
# Logging to the sentry.replays.slow_click namespace because
# its the only one configured to use BigQuery at the moment.
#
# NOTE: Needs an ops request to create a new dataset.
"sentry.replays.slow_click",
extra={
"event_type": "canvas_size",
"org_id": org_id,
"project_id": project_id,
"replay_id": replay_id,
"size": len(json.dumps(event)),
},
)
def get_user_actions(
project_id: int,
replay_id: str,
events: list[dict[str, Any]],
replay_event: dict[str, Any] | None,
) -> list[ReplayActionsEventPayloadClick]:
"""Return a list of ReplayActionsEventPayloadClick types.
The node object is a partially destructured HTML element with an additional RRWeb
identifier included. Node objects are not recursive and truncate their children. Text is
extracted and stored on the textContent key.
For example, the follow DOM element:
<div id="a" class="b c">Hello<span>, </span>world!</div>
Would be destructured as:
{
"id": 217,
"tagName": "div",
"attributes": {"id": "a", "class": "b c"},
"textContent": "Helloworld!"
}
"""
result: list[ReplayActionsEventPayloadClick] = []
for event in _iter_custom_events(events):
if len(result) == 20:
break
tag = event.get("data", {}).get("tag")
if tag == "breadcrumb":
click = _handle_breadcrumb(event, project_id, replay_id, replay_event)
if click is not None:
result.append(click)
# look for request / response breadcrumbs and report metrics on them
if tag == "performanceSpan":
_handle_resource_metric_event(event)
# log the SDK options sent from the SDK 1/500 times
if tag == "options" and random.randint(0, 499) < 1:
_handle_options_logging_event(project_id, replay_id, event)
# log large dom mutation breadcrumb events 1/100 times
payload = event.get("data", {}).get("payload", {})
if (
isinstance(payload, dict)
and tag == "breadcrumb"
and payload.get("category") == "replay.mutations"
and random.randint(0, 99) < 1
):
_handle_mutations_event(project_id, replay_id, event)
return result
def _get_testid(container: dict[str, str]) -> str:
return (
container.get("testId")
or container.get("data-testid")
or container.get("data-test-id")
or ""
)
def _initialize_publisher() -> KafkaPublisher:
global replay_publisher
if replay_publisher is None:
config = kafka_config.get_topic_definition(Topic.INGEST_REPLAY_EVENTS)
replay_publisher = KafkaPublisher(
kafka_config.get_kafka_producer_cluster_options(config["cluster"])
)
return replay_publisher
def encode_as_uuid(message: str) -> str:
return str(uuid.UUID(md5(message.encode()).hexdigest()))
def create_click_event(
payload: dict[str, Any],
replay_id: str,
is_dead: bool,
is_rage: bool,
) -> ReplayActionsEventPayloadClick | None:
node = payload.get("data", {}).get("node")
if node is None:
return None
attributes = node.get("attributes", {})
# The class attribute can have extra white-space contained within. We need to filter them out
# before truncating the list.
classes = _parse_classes(attributes.get("class", ""))
return {
"node_id": node["id"],
"tag": node["tagName"][:32],
"id": attributes.get("id", "")[:64],
"class": classes,
"text": node["textContent"][:1024],
"role": attributes.get("role", "")[:32],
"alt": attributes.get("alt", "")[:64],
"testid": _get_testid(attributes)[:64],
"aria_label": attributes.get("aria-label", "")[:64],
"title": attributes.get("title", "")[:64],
"component_name": attributes.get("data-sentry-component", "")[:64],
"is_dead": int(is_dead),
"is_rage": int(is_rage),
"timestamp": int(payload["timestamp"]),
"event_hash": encode_as_uuid(
"{}{}{}".format(replay_id, str(payload["timestamp"]), str(node["id"]))
),
}
def _parse_classes(classes: str) -> list[str]:
return list(filter(lambda n: n != "", classes.split(" ")))[:10]
def _should_report_rage_click_issue(project_id: int) -> bool:
project = Project.objects.get(id=project_id)
def _project_has_feature_enabled() -> bool:
"""
Check if the project has the feature flag enabled,
This is controlled by Sentry admins for release of the feature
"""
return features.has(
"organizations:session-replay-rage-click-issue-creation",
project.organization,
)
def _project_has_option_enabled() -> bool:
"""
Check if the project has the option enabled,
This is controlled by the project owner, and is a permanent setting
"""
return project.get_option("sentry:replay_rage_click_issues")
return all([_project_has_feature_enabled(), _project_has_option_enabled()])
def _iter_custom_events(events: list[dict[str, Any]]) -> Generator[dict[str, Any], None, None]:
for event in events:
if event.get("type") == 5:
yield event
def _handle_resource_metric_event(event: dict[str, Any]) -> None:
if event["data"].get("payload", {}).get("op") not in ("resource.fetch", "resource.xhr"):
return None
event_payload_data = event["data"]["payload"]["data"]
# The data key is sometimes submitted as an string. If any type other than a
# dictionary is provided default the value to an empty dict.
#
# TODO: Refactor this area in a later release.
if not isinstance(event_payload_data, dict):
event_payload_data = {}
if "requestBodySize" in event_payload_data: # 7.44 and 7.45
metrics.distribution(
"replays.usecases.ingest.request_body_size",
event_payload_data["requestBodySize"],
unit="byte",
)
elif request := event_payload_data.get("request"):
if isinstance(request, dict) and "size" in request:
metrics.distribution(
"replays.usecases.ingest.request_body_size",
request["size"],
unit="byte",
)
if "responseBodySize" in event_payload_data: # 7.44 and 7.45
metrics.distribution(
"replays.usecases.ingest.response_body_size",
event_payload_data["responseBodySize"],
unit="byte",
)
elif response := event_payload_data.get("response"):
if isinstance(response, dict) and "size" in response:
metrics.distribution(
"replays.usecases.ingest.response_body_size",
response["size"],
unit="byte",
)
def _handle_options_logging_event(project_id: int, replay_id: str, event: dict[str, Any]) -> None:
# log the SDK options sent from the SDK 1/500 times
if random.randint(0, 499) < 1:
log = event["data"].get("payload", {}).copy()
log["project_id"] = project_id
log["replay_id"] = replay_id
logger.info("SDK Options:", extra=log)
def _handle_mutations_event(project_id: int, replay_id: str, event: dict[str, Any]) -> None:
if (
event.get("data", {}).get("payload", {}).get("category") == "replay.mutations"
and random.randint(0, 99) < 1
):
log = event["data"].get("payload", {}).copy()
log["project_id"] = project_id
log["replay_id"] = replay_id
logger.info("Large DOM Mutations List:", extra=log)
def _handle_breadcrumb(
event: dict[str, Any], project_id: int, replay_id: str, replay_event: dict[str, Any] | None
) -> ReplayActionsEventPayloadClick | None:
click = None
payload = event["data"].get("payload", {})
if not isinstance(payload, dict):
return None
category = payload.get("category")
if category == "ui.slowClickDetected":
is_timeout_reason = payload["data"].get("endReason") == "timeout"
is_target_tagname = payload["data"].get("node", {}).get("tagName") in (
"a",
"button",
"input",
)
timeout = payload["data"].get("timeAfterClickMs", 0) or payload["data"].get(
"timeafterclickms", 0
)
if is_timeout_reason and is_target_tagname and timeout >= 7000:
is_rage = (
payload["data"].get("clickCount", 0) or payload["data"].get("clickcount", 0)
) >= 5
click = create_click_event(payload, replay_id, is_dead=True, is_rage=is_rage)
if click is not None:
if is_rage:
metrics.incr("replay.rage_click_detected")
if _should_report_rage_click_issue(project_id):
if replay_event is not None:
report_rage_click_issue_with_replay_event(
project_id,
replay_id,
payload["timestamp"],
payload["message"],
payload["data"]["url"],
payload["data"]["node"],
replay_event,
)
else:
report_rage_click_issue.delay(
project_id, replay_id, cast(SentryEvent, event)
)
# Log the event for tracking.
log = event["data"].get("payload", {}).copy()
log["project_id"] = project_id
log["replay_id"] = replay_id
log["dom_tree"] = log.pop("message")
logger.info("sentry.replays.slow_click", extra=log)
return click
elif category == "ui.multiClick":
# Log the event for tracking.
log = event["data"].get("payload", {}).copy()
log["project_id"] = project_id
log["replay_id"] = replay_id
log["dom_tree"] = log.pop("message")
logger.info("sentry.replays.slow_click", extra=log)
elif category == "ui.click":
click = create_click_event(payload, replay_id, is_dead=False, is_rage=False)
if click is not None:
return click
return None