diff --git a/src/sentry/constants.py b/src/sentry/constants.py index 1562c2fa1b18..c08a5191a52a 100644 --- a/src/sentry/constants.py +++ b/src/sentry/constants.py @@ -375,6 +375,7 @@ def parse_log_level(level: str | None) -> LogLevel | None: "application/x-il2cpp-json": "il2cpp", "application/x-portable-pdb": "portablepdb", "application/x-dartsymbolmap+json": "dartsymbolmap", + "application/x-wasm-sourcemap+json": "wasmsourcemap", } NATIVE_UNKNOWN_STRING = "" diff --git a/src/sentry/models/debugfile.py b/src/sentry/models/debugfile.py index 52f7b5faf4ad..61681e21889b 100644 --- a/src/sentry/models/debugfile.py +++ b/src/sentry/models/debugfile.py @@ -95,6 +95,8 @@ def _dif_file_extension(file_format: str, file_type: str | None) -> str: return ".json" if file_format == "dartsymbolmap": return ".json" + if file_format == "wasmsourcemap": + return ".wasm.map" return "" @@ -445,7 +447,11 @@ def clean_redundant_difs(project: Project, debug_id: str) -> None: bcsymbolmap_seen = False uuidmap_seen = False il2cpp_seen = False - for i, dif in enumerate(difs): + wasmsourcemap_seen = False + # Whether a file has been kept by the generic rule below. The companion files above share the + # debug id but never add to `all_features`, so they must not count as a newer file there. + generic_seen = False + for dif in difs: mime_type = dif.get_content_type() if mime_type == DIF_MIMETYPES["bcsymbolmap"]: if not bcsymbolmap_seen: @@ -462,13 +468,19 @@ def clean_redundant_difs(project: Project, debug_id: str) -> None: il2cpp_seen = True else: dif.delete() + elif mime_type == DIF_MIMETYPES["wasmsourcemap"]: + if not wasmsourcemap_seen: + wasmsourcemap_seen = True + else: + dif.delete() else: # We always keep the latest file. If it has no features, likely the # previous files did not have features either and will be removed, or we # keep both. Subsequent uploads will remove this file later. - if i > 0 and dif.features <= all_features: + if generic_seen and dif.features <= all_features: dif.delete() else: + generic_seen = True all_features.update(dif.features) @@ -501,6 +513,7 @@ def _get_dif_object_name(meta: DifMeta) -> str: "uuidmap", "il2cpp", "dartsymbolmap", + "wasmsourcemap", ): return meta.name if meta.file_format == "breakpad": @@ -829,12 +842,102 @@ class DifKind(enum.Enum): Object = enum.auto() BcSymbolMap = enum.auto() UuidMap = enum.auto() - Il2Cpp = enum.auto() + # A JSON object: an il2cpp line mapping or a WASM source map. They can only be told apart + # once the JSON is parsed, see `detect_dif_from_path`. + JsonObject = enum.auto() DartSymbolMap = enum.auto() # TODO(flub): should we include proguard? The tradeoff is that we'd be matching the # regex of it twice. That cost is probably not too great to worry about. +def _load_json(path: str) -> Any: + try: + with open(path, "rb") as fp: + return json.load(fp) + except json.JSONDecodeError as e: + logger.debug("File failed to load as JSON: %s", path) + raise BadDif("Invalid JSON: %s" % e) + + +def _is_source_map(data: Any) -> bool: + """Whether a parsed JSON document looks like a source map (any version).""" + return ( + isinstance(data, dict) and "version" in data and ("mappings" in data or "sections" in data) + ) + + +def _try_normalize_debug_id(debug_id: str) -> str | None: + try: + return normalize_debug_id(debug_id) + except SymbolicError: + return None + + +def _wasm_source_map_debug_id(data: dict[str, Any], debug_id: str | None) -> str: + """The normalized debug id to store a WASM source map under. + + A map can carry its own id in `debugId` (the source map debug id proposal, which Emscripten + fills with the module's build id) or in the legacy `debug_id`. That id wins over the one the + client sends. Without either, the client must send the module's build id. + """ + embedded = data.get("debugId") + if embedded is None: + embedded = data.get("debug_id") + + if embedded is None: + if debug_id is None: + raise BadDif("Missing debug_id for wasmsourcemap") + try: + return normalize_debug_id(debug_id) + except SymbolicError as e: + raise BadDif("Invalid debug_id for wasmsourcemap: %s" % e) + + if not isinstance(embedded, str): + raise BadDif("Invalid debugId in wasmsourcemap: %r" % embedded) + try: + embedded = normalize_debug_id(embedded) + except SymbolicError as e: + raise BadDif("Invalid debugId in wasmsourcemap: %s" % e) + + if debug_id is not None and _try_normalize_debug_id(debug_id) != embedded: + # Symbolicator looks up the map by the module's build id. A map stamped with another id is + # stored under its own id, so it is never paired with the module it was uploaded next to. + logger.warning( + "wasmsourcemap.debug_id_mismatch", + extra={"embedded_debug_id": embedded, "debug_id": debug_id}, + ) + return embedded + + +def _detect_wasm_source_map( + data: dict[str, Any], path: str, name: str | None, debug_id: str | None +) -> list[DifMeta]: + if data["version"] != 3: + raise BadDif("Unsupported source map version: %r" % data["version"]) + if "sections" in data: + raise BadDif("Index source maps are not supported") + debug_id = _wasm_source_map_debug_id(data, debug_id) + logger.debug("File loaded as wasmsourcemap: %s", path) + return [ + DifMeta( + file_format="wasmsourcemap", + arch="any", + debug_id=debug_id, + legacy_debug_id=wasm_legacy_debug_id(debug_id), + name=name, + path=path, + data={"features": []}, + ) + ] + + +def _detect_il2cpp(path: str, name: str | None, debug_id: str | None) -> list[DifMeta]: + if debug_id is None: + raise BadDif("Missing debug_id for il2cpp") + logger.debug("File loaded as il2cpp: %s", path) + return [DifMeta(file_format="il2cpp", arch="any", debug_id=debug_id, name=name, path=path)] + + def determine_dif_kind(path: str) -> DifKind: """Returns the :class:`DifKind` detected at `path`.""" # TODO(flub): Using just the filename might be sufficient. But the cost of opening a @@ -846,8 +949,8 @@ def determine_dif_kind(path: str) -> DifKind: return DifKind.BcSymbolMap elif data.startswith(b" None: # The file that we find should have the legacy debug ID. assert response.data[0]["debugId"] == "10da03eb-5d63-d750-faab-0fb8e7cc12a1" + def test_wasm_source_map_listed_with_its_module(self) -> None: + self._upload_wasm() + + # The source map shares the debug id of the module it was built with. + debug_id = "da03eb5d-63d7-50fa-ab0f-b8e7cc12a1c3" + source_map = b'{"version": 3, "sources": ["src/main.c"], "names": [], "mappings": "AAAA"}' + blob = FileBlob.from_file_with_organization(ContentFile(source_map), self.organization) + assemble_dif( + project_id=self.project.id, + name="index.wasm.map", + checksum=sha1(source_map).hexdigest(), + chunks=[blob.checksum], + debug_id=debug_id, + ) + + # This is the query Symbolicator sends to find the files for a module. + response = self.client.get(f"{self.url}?debug_id={debug_id}") + assert response.status_code == 200, response.content + difs_by_type = {dif["symbolType"]: dif for dif in response.data} + assert sorted(difs_by_type) == ["wasm", "wasmsourcemap"] + + source_map_dif = difs_by_type["wasmsourcemap"] + assert source_map_dif["debugId"] == debug_id + assert source_map_dif["objectName"] == "index.wasm.map" + + # Symbolicator then downloads the file by id. + response = self.client.get(f"{self.url}?id={source_map_dif['id']}") + self._assert_successful_download(response, source_map, filename=f"{debug_id}.wasm.map") + + # Events from SDKs with the old WASM build id bug send the legacy id (INGEST-1282). + # The map must be found by it too, not only the module. + response = self.client.get(f"{self.url}?debug_id=10da03eb-5d63-d750-faab-0fb8e7cc12a1") + assert response.status_code == 200, response.content + assert sorted(dif["symbolType"] for dif in response.data) == ["wasm", "wasmsourcemap"] + def _do_test_dsyms_by_debugid_and_codeid( self, query: tuple[str, ...], files: list[tuple[bool, str, str]] ) -> None: diff --git a/tests/sentry/models/test_debugfile.py b/tests/sentry/models/test_debugfile.py index 6fd2cc6731d7..e4b45f430f1e 100644 --- a/tests/sentry/models/test_debugfile.py +++ b/tests/sentry/models/test_debugfile.py @@ -5,6 +5,7 @@ import time import zipfile from io import BytesIO +from pathlib import Path from typing import IO, Any from unittest.mock import MagicMock, patch @@ -17,6 +18,7 @@ from symbolic.debuginfo import Archive from sentry.models.debugfile import ( + BadDif, DifMeta, ProjectDebugFile, create_debug_file_from_dif, @@ -193,6 +195,28 @@ def test_file_extension_dartsymbolmap(self) -> None: # Verify that file_extension returns .json assert dif.file_extension == ".json" + def test_file_extension_wasmsourcemap(self) -> None: + """Test that wasmsourcemap files return .wasm.map file extension.""" + # Create a file with wasmsourcemap content type + file = self.create_file( + name="main.dart.wasm.map", + type="project.dif", + headers={"Content-Type": "application/x-wasm-sourcemap+json"}, + ) + + # Create a ProjectDebugFile + dif = self.create_dif_file( + file=file, + object_name="main.dart.wasm.map", + cpu_name="any", + debug_id="bda18fd8-5d4a-4eb8-9302-2d6bfad846b1", + data={}, + ) + + # Verify that file_extension returns .wasm.map and that the format returns wasmsourcemap + assert dif.file_extension == ".wasm.map" + assert dif.file_format == "wasmsourcemap" + def test_file_extension_macho_dbg(self) -> None: """Test that macho files return empty file extension.""" file = File.objects.create( @@ -594,6 +618,79 @@ def test_skip_redundant_dif(self) -> None: assert not created2 assert dif1 == dif2 + def test_keep_wasm_source_map_with_its_module(self) -> None: + # The CLI may upload the map before the module. Both share the debug id. + file = self.create_stored_file(b"source map") + source_map, created1 = self.create_dif( + file=file, file_format="wasmsourcemap", arch="any", data={"features": []} + ) + + file = self.create_stored_file(b"wasm module") + module, created2 = self.create_dif( + file=file, file_format="wasm", arch="wasm32", data={"features": ["symtab", "debug"]} + ) + + assert created1 and created2 + assert ProjectDebugFile.objects.filter(id=source_map.id).exists() + assert ProjectDebugFile.objects.filter(id=module.id).exists() + + def test_keep_module_without_features_when_map_is_newer(self) -> None: + # A fully stripped module has no features. The newer map must not make the generic rule + # treat it as redundant. + file = self.create_stored_file(b"stripped wasm module") + module, _ = self.create_dif( + file=file, file_format="wasm", arch="wasm32", data={"features": []} + ) + + file = self.create_stored_file(b"source map") + source_map, _ = self.create_dif( + file=file, file_format="wasmsourcemap", arch="any", data={"features": []} + ) + + assert ProjectDebugFile.objects.filter(id=module.id).exists() + assert ProjectDebugFile.objects.filter(id=source_map.id).exists() + + def test_remove_older_module_when_map_is_newest(self) -> None: + # The generic rule still replaces an older module, even when a map is the newest file. + file = self.create_stored_file(b"first wasm module") + old_module, _ = self.create_dif( + file=file, file_format="wasm", arch="wasm32", data={"features": []} + ) + + file = self.create_stored_file(b"second wasm module") + new_module, _ = self.create_dif( + file=file, file_format="wasm", arch="wasm32", data={"features": []} + ) + + file = self.create_stored_file(b"source map") + source_map, _ = self.create_dif( + file=file, file_format="wasmsourcemap", arch="any", data={"features": []} + ) + + assert not ProjectDebugFile.objects.filter(id=old_module.id).exists() + assert ProjectDebugFile.objects.filter(id=new_module.id).exists() + assert ProjectDebugFile.objects.filter(id=source_map.id).exists() + + def test_remove_older_wasm_source_map(self) -> None: + file = self.create_stored_file(b"wasm module") + module, _ = self.create_dif( + file=file, file_format="wasm", arch="wasm32", data={"features": ["symtab", "debug"]} + ) + + file = self.create_stored_file(b"first source map") + old_map, _ = self.create_dif( + file=file, file_format="wasmsourcemap", arch="any", data={"features": []} + ) + + file = self.create_stored_file(b"second source map") + new_map, _ = self.create_dif( + file=file, file_format="wasmsourcemap", arch="any", data={"features": []} + ) + + assert not ProjectDebugFile.objects.filter(id=old_map.id).exists() + assert ProjectDebugFile.objects.filter(id=new_map.id).exists() + assert ProjectDebugFile.objects.filter(id=module.id).exists() + def test_remove_redundant_dif(self) -> None: file = self.create_stored_file(b"first debug symbols") dif1, created1 = self.create_dif(file=file, data={"features": ["debug"]}) @@ -833,8 +930,8 @@ def test_dartsymbolmap_file_odd_array_fails() -> None: def test_dartsymbolmap_file_dict_format() -> None: """Test that dict format JSON files are detected as Il2Cpp, not dartsymbolmap.""" - # Note: Files starting with '{' are detected as Il2Cpp files, not dartsymbolmap - # This is because determine_dif_kind() checks for '{' before '[' and assigns Il2Cpp + # Note: Files starting with '{' are detected as JsonObject files, not dartsymbolmap + # This is because determine_dif_kind() checks for '{' before '[' and assigns JsonObject with tempfile.NamedTemporaryFile(mode="w", suffix=".json") as f: f.write('{"xyz": "ExceptionClass", "abc": "DatabaseError"}') f.flush() @@ -876,3 +973,104 @@ def test_dartsymbolmap_file_missing_debug_id() -> None: with pytest.raises(BadDif, match="Missing debug_id for dartsymbolmap"): detect_dif_from_path(f.name, name="dartsymbolmap.json", debug_id=None) + + +WASM_SOURCE_MAP = '{"version": 3, "sources": ["src/main.c"], "names": [], "mappings": "AAAA"}' + + +def _detect_json_file(tmp_path: Path, content: str, debug_id: str | None) -> list[DifMeta]: + path = tmp_path / "main.wasm.map" + path.write_text(content) + return detect_dif_from_path(str(path), name="main.wasm.map", debug_id=debug_id) + + +def test_wasm_source_map_detected(tmp_path: Path) -> None: + detected = _detect_json_file( + tmp_path, WASM_SOURCE_MAP, debug_id="BDA18FD8-5D4A-4EB8-9302-2D6BFAD846B1" + ) + + assert len(detected) == 1 + dif_meta = detected[0] + assert dif_meta.file_format == "wasmsourcemap" + assert dif_meta.arch == "any" + # Symbolicator looks files up by the normalized (lowercase) debug id. + assert dif_meta.debug_id == "bda18fd8-5d4a-4eb8-9302-2d6bfad846b1" + assert dif_meta.legacy_debug_id == "10bda18f-d85d-4a4e-b893-022d6bfad846" + assert dif_meta.name == "main.wasm.map" + assert dif_meta.data == {"features": []} + + +def test_wasm_source_map_unsupported_version(tmp_path: Path) -> None: + content = '{"version": 4, "sources": [], "names": [], "mappings": "AAAA"}' + + with pytest.raises(BadDif, match="Unsupported source map version: 4"): + _detect_json_file(tmp_path, content, debug_id="bda18fd8-5d4a-4eb8-9302-2d6bfad846b1") + + +def test_wasm_source_map_index_map_rejected(tmp_path: Path) -> None: + content = '{"version": 3, "sections": [{"offset": {"line": 0, "column": 0}, "map": {}}]}' + + with pytest.raises(BadDif, match="Index source maps are not supported"): + _detect_json_file(tmp_path, content, debug_id="bda18fd8-5d4a-4eb8-9302-2d6bfad846b1") + + +def test_wasm_source_map_missing_debug_id(tmp_path: Path) -> None: + with pytest.raises(BadDif, match="Missing debug_id for wasmsourcemap"): + _detect_json_file(tmp_path, WASM_SOURCE_MAP, debug_id=None) + + +def test_wasm_source_map_invalid_debug_id(tmp_path: Path) -> None: + with pytest.raises(BadDif, match="Invalid debug_id for wasmsourcemap"): + _detect_json_file(tmp_path, WASM_SOURCE_MAP, debug_id="not-a-debug-id") + + +def test_wasm_source_map_embedded_debug_id(tmp_path: Path) -> None: + # Emscripten writes the module's build id into the map, without hyphens. + content = '{"version": 3, "debugId": "3B5EA884827C57BDAF43D4AEE910713C", "mappings": "AAAA"}' + + detected = _detect_json_file(tmp_path, content, debug_id=None) + + assert len(detected) == 1 + assert detected[0].file_format == "wasmsourcemap" + assert detected[0].debug_id == "3b5ea884-827c-57bd-af43-d4aee910713c" + + +def test_wasm_source_map_embedded_debug_id_wins(tmp_path: Path) -> None: + content = ( + '{"version": 3, "debugId": "3b5ea884-827c-57bd-af43-d4aee910713c", "mappings": "AAAA"}' + ) + + detected = _detect_json_file(tmp_path, content, debug_id="bda18fd8-5d4a-4eb8-9302-2d6bfad846b1") + + assert len(detected) == 1 + assert detected[0].debug_id == "3b5ea884-827c-57bd-af43-d4aee910713c" + + +def test_wasm_source_map_legacy_embedded_debug_id(tmp_path: Path) -> None: + content = ( + '{"version": 3, "debug_id": "3b5ea884-827c-57bd-af43-d4aee910713c", "mappings": "AAAA"}' + ) + + detected = _detect_json_file(tmp_path, content, debug_id=None) + + assert len(detected) == 1 + assert detected[0].debug_id == "3b5ea884-827c-57bd-af43-d4aee910713c" + + +@pytest.mark.parametrize("embedded", ['"not-a-debug-id"', "42"]) +def test_wasm_source_map_invalid_embedded_debug_id(tmp_path: Path, embedded: str) -> None: + content = '{"version": 3, "debugId": %s, "mappings": "AAAA"}' % embedded + + with pytest.raises(BadDif, match="Invalid debugId in wasmsourcemap"): + _detect_json_file(tmp_path, content, debug_id="bda18fd8-5d4a-4eb8-9302-2d6bfad846b1") + + +def test_il2cpp_still_detected_alongside_wasm_source_maps(tmp_path: Path) -> None: + """A JSON object that is not a source map keeps being stored as il2cpp.""" + content = '{"/src/Game.cpp": {"12": {"cs_file": "Game.cs", "cs_line": 3}}}' + + detected = _detect_json_file(tmp_path, content, debug_id="bda18fd8-5d4a-4eb8-9302-2d6bfad846b1") + + assert len(detected) == 1 + assert detected[0].file_format == "il2cpp" + assert detected[0].data is None diff --git a/tests/sentry/tasks/test_assemble.py b/tests/sentry/tasks/test_assemble.py index ee8e5b67653c..90422d65994f 100644 --- a/tests/sentry/tasks/test_assemble.py +++ b/tests/sentry/tasks/test_assemble.py @@ -244,6 +244,29 @@ def test_assemble_debug_id_override(self) -> None: assert dif.get_content_type() == "text/x-breakpad" assert dif.debug_id == "67e9247c-814e-392b-a027-dbde6748fcbf-beef" + def test_assemble_wasm_source_map(self) -> None: + source_map = b'{"version": 3, "sources": ["src/main.c"], "names": [], "mappings": "AAAA"}' + blob = FileBlob.from_file_with_organization(ContentFile(source_map), self.organization) + total_checksum = sha1(source_map).hexdigest() + + assemble_dif( + project_id=self.project.id, + name="main.wasm.map", + checksum=total_checksum, + chunks=[blob.checksum], + debug_id="DA03EB5D-63D7-50FA-AB0F-B8E7CC12A1C3", + ) + + status, _ = get_assemble_status(AssembleTask.DIF, self.project.id, total_checksum) + assert status == ChunkFileState.OK + + dif = ProjectDebugFile.objects.get(project_id=self.project.id, checksum=total_checksum) + assert dif.get_content_type() == "application/x-wasm-sourcemap+json" + assert dif.file_format == "wasmsourcemap" + # Symbolicator looks files up by the normalized (lowercase) debug id. + assert dif.debug_id == "da03eb5d-63d7-50fa-ab0f-b8e7cc12a1c3" + assert dif.object_name == "main.wasm.map" + @requires_objectstore class ArtifactBundleBackendChangeTest(BaseAssembleTest):