This is an automated email from the ASF dual-hosted git repository. alexandrusoare pushed a commit to branch alexandrusoare/feat/canvas-instrumentation in repository https://gitbox.apache.org/repos/asf/superset.git
commit 1be1f10c19f0d72e8c69f7d44fd66ac293b05f40 Author: alexandrusoare <[email protected]> AuthorDate: Tue Nov 17 17:05:38 2026 +0200 feat(canvas): make canvas events attributable and failures countable Canvas routes were already instrumented, but nothing they recorded could be tied to a canvas: `logs` has an integer column for a dashboard or a chart and none for a canvas, so every canvas row landed with both null. Failures were worse than unattributed -- `_handle_canvas_errors` logged on one of its ten branches, and `get_placement_data` handled six error cases inline without logging any, so a failing widget query left no backend trace at all. Add `logs.canvas_id` and register `Canvas` in `LOG_OBJECT_ID_COLUMNS`, which is enough for every route that names a canvas in its URL. The column travels to `log()` as a keyword argument rather than widening the abstract signature, so a custom `EVENT_LOGGER` written before the column existed keeps working untouched -- there is a test for exactly that. The draft routes cannot be covered that way: a draft is named by the `X-Canvas-Draft` header precisely so the token stays out of logs, which also means there is no id in the URL to resolve. Those six, plus `post` whose canvas has no id until the command runs, report it themselves through the existing `allow_extra_payload` seam. Record failures centrally in `_handle_canvas_errors`, plus the inline branches it cannot see. Each one increments `canvas.error.<ExceptionClass>` and writes a `canvas_error` row. The canvas id stays out of the statsd key -- that would make the series unbounded -- and `include_request_data=False` keeps the ops array and the runtime filter values out of `logs.json`. The exception message is left out too, since a command error can quote user input. Reporting is best-effort throughout: it must never mask the error it is reporting. --- superset/canvas/api.py | 128 +++++++++++-- ...-17_10-00_c4a7e9d21f08_add_canvas_id_to_logs.py | 51 ++++++ superset/models/core.py | 1 + superset/utils/log.py | 32 +++- superset/views/log/api.py | 2 + tests/unit_tests/canvas/telemetry_test.py | 202 +++++++++++++++++++++ tests/unit_tests/utils/log_tests.py | 81 +++++++++ 7 files changed, 476 insertions(+), 21 deletions(-) diff --git a/superset/canvas/api.py b/superset/canvas/api.py index 3b99edef53a..00c5be98a0a 100644 --- a/superset/canvas/api.py +++ b/superset/canvas/api.py @@ -93,10 +93,11 @@ from superset.constants import MODEL_API_RW_METHOD_PERMISSION_MAP, RouteMethod from superset.daos.canvas import CanvasDAO from superset.daos.exceptions import DatasourceNotFound from superset.exceptions import QueryObjectValidationError, SupersetSecurityException -from superset.extensions import event_logger, security_manager +from superset.extensions import event_logger, security_manager, stats_logger_manager from superset.models.canvas import Canvas from superset.subjects.filters import FilterRelatedSubjects, subject_type_filter from superset.utils import json +from superset.utils.log import get_object_ids_from_view_args from superset.versioning.api_helpers import ( list_versions_endpoint, PathEntityResponseError, @@ -115,6 +116,57 @@ from superset.views.filters import BaseFilterRelatedUsers, FilterRelatedUsers logger = logging.getLogger(__name__) +def _report_canvas_error( + api: CanvasRestApi, + ex: Exception, + status: int, + scope: str = "command", +) -> None: + """Count and record a canvas failure. + + A canvas route already logs the request, but ``_handle_canvas_errors`` is + the innermost decorator: it turns the exception into a response before the + route's own event logger runs, so the failure's type never reaches that + row. This writes a separate one. + + Only the exception class name, the status, the scope and the canvas id are + recorded. The message is left out on purpose -- a command error can quote + user input -- and ``include_request_data=False`` keeps the request body, + which is an ops array for draft writes and filter values for placement + data, out of ``logs.json``. + + Reporting never changes the outcome of a request, and never masks the error + being reported, so every failure here is swallowed. + """ + try: + error_type = type(ex).__name__ + canvas_id = get_object_ids_from_view_args(api, request.view_args or {}).get( + "canvas_id" + ) + # The class name is a Python identifier from a closed set, so the key + # space stays bounded. The canvas id deliberately stays out of it: + # per-canvas analysis is what ``logs.canvas_id`` is for. + stats_logger_manager.instance.incr(f"canvas.error.{error_type}") + logger.warning( + "Canvas request failed: error_type=%s status=%s scope=%s canvas_id=%s", + error_type, + status, + scope, + canvas_id, + ) + event_logger.log_with_context( + action="canvas_error", + log_to_statsd=False, + include_request_data=False, + canvas_id=canvas_id, + error_type=error_type, + status=status, + scope=scope, + ) + except Exception: # pylint: disable=broad-except + logger.debug("Canvas error reporting failed", exc_info=True) + + def _handle_canvas_errors( f: Callable[..., Response], ) -> Callable[..., Response]: @@ -126,35 +178,50 @@ def _handle_canvas_errors( CanvasNotFoundError, CanvasPlacementNotFoundError, CanvasVersionNotFoundError, - ): + ) as ex: + _report_canvas_error(self, ex, 404) return self.response_404() except CanvasDraftNotFoundError as ex: + _report_canvas_error(self, ex, 404) return self.response(404, message="Not found", error_type=ex.recovery_type) - except CanvasForbiddenError: + except CanvasForbiddenError as ex: + _report_canvas_error(self, ex, 403) return self.response_403() except CanvasInvalidError as ex: + _report_canvas_error(self, ex, 422) return self.response_422(message=ex.normalized_messages()) except ( DefinitionConflictError, DefinitionInvalidError, DraftConflictError, ) as ex: + _report_canvas_error(self, ex, ex.status) return self.response(ex.status, **ex.to_payload()) except CanvasPlacementUnboundError as ex: + _report_canvas_error(self, ex, 422) return self.response_422(message=str(ex.message)) except DefinitionVersionError as ex: + _report_canvas_error(self, ex, 422) return self.response_422(message=str(ex)) except ( CanvasCreateFailedError, CanvasUpdateFailedError, CanvasDeleteFailedError, ) as ex: + _report_canvas_error(self, ex, 422) logger.exception("Canvas write failed") return self.response_422(message=str(ex)) return wrapped +# Adds fields to the request's own log row. ``allow_extra_payload=True`` hands a +# route one of these: the draft routes need it because a draft is named by a +# header, so there is no canvas id in the URL for the event logger to resolve on +# its own, and ``post`` needs it because the id does not exist until the command +# has run. +LogPayload = Callable[..., None] + # Draft tokens travel in a header, never in a URL, so they stay out of logs. DRAFT_TOKEN_HEADER = "X-Canvas-Draft" # noqa: S105 # Reads a placement as a version saved it, for previewing that version. @@ -376,9 +443,11 @@ class CanvasRestApi(BaseSupersetModelRestApi): @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.post", log_to_statsd=False, + # The canvas has no id until the command runs, so the route reports it. + allow_extra_payload=True, ) @_handle_canvas_errors - def post(self) -> Response: + def post(self, *, add_extra_log_payload: LogPayload) -> Response: """Create a canvas. --- post: @@ -413,6 +482,7 @@ class CanvasRestApi(BaseSupersetModelRestApi): except ValidationError as error: return self.response_400(message=error.messages) canvas = CreateCanvasCommand(item).run() + add_extra_log_payload(canvas_id=canvas.id) return self.response(201, id=canvas.id, uuid=str(canvas.uuid)) @expose("/<int:pk>", methods=("PUT",)) @@ -784,9 +854,10 @@ class CanvasRestApi(BaseSupersetModelRestApi): @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.get_draft", log_to_statsd=False, + allow_extra_payload=True, ) @_handle_canvas_errors - def get_draft(self) -> Response: + def get_draft(self, *, add_extra_log_payload: LogPayload) -> Response: """Get the draft named by the `X-Canvas-Draft` header. --- get: @@ -798,6 +869,7 @@ class CanvasRestApi(BaseSupersetModelRestApi): $ref: '#/components/responses/404' """ draft = load_draft(_draft_token()) + add_extra_log_payload(canvas_id=draft.canvas_id) return self.response(200, result=draft_payload(draft)) @expose("/draft", methods=("PATCH",)) @@ -809,9 +881,10 @@ class CanvasRestApi(BaseSupersetModelRestApi): f"{self.__class__.__name__}.apply_draft_operations" ), log_to_statsd=False, + allow_extra_payload=True, ) @_handle_canvas_errors - def apply_draft_operations(self) -> Response: + def apply_draft_operations(self, *, add_extra_log_payload: LogPayload) -> Response: """Apply operations to the draft named by the `X-Canvas-Draft` header. --- patch: @@ -833,10 +906,14 @@ class CanvasRestApi(BaseSupersetModelRestApi): try: body = DraftOperationsRequest.model_validate(request.get_json(silent=True)) except PydanticValidationError as ex: + # A malformed ops payload is a real failure mode for an agent + # writing to a draft, and otherwise leaves no trace. + _report_canvas_error(self, ex, 400, scope="draft_ops") return self.response(400, message=_pydantic_errors(ex)) draft, ops = ApplyCanvasDraftOperationsCommand( _draft_token(), body.revision, body.ops ).run() + add_extra_log_payload(canvas_id=draft.canvas_id) return self.response(200, result={**draft_payload(draft), "ops": ops}) @expose("/draft/undo", methods=("POST",)) @@ -846,9 +923,10 @@ class CanvasRestApi(BaseSupersetModelRestApi): @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.undo_draft", log_to_statsd=False, + allow_extra_payload=True, ) @_handle_canvas_errors - def undo_draft(self) -> Response: + def undo_draft(self, *, add_extra_log_payload: LogPayload) -> Response: """Step the draft named by the `X-Canvas-Draft` header back one request. --- post: @@ -880,7 +958,7 @@ class CanvasRestApi(BaseSupersetModelRestApi): 409: description: The draft or the canvas changed """ - return self._rewind_draft(forward=False) + return self._rewind_draft(forward=False, report=add_extra_log_payload) @expose("/draft/redo", methods=("POST",)) @protect() @@ -889,9 +967,10 @@ class CanvasRestApi(BaseSupersetModelRestApi): @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.redo_draft", log_to_statsd=False, + allow_extra_payload=True, ) @_handle_canvas_errors - def redo_draft(self) -> Response: + def redo_draft(self, *, add_extra_log_payload: LogPayload) -> Response: """Put back the request the draft last stepped off. --- post: @@ -920,9 +999,9 @@ class CanvasRestApi(BaseSupersetModelRestApi): 409: description: The draft or the canvas changed """ - return self._rewind_draft(forward=True) + return self._rewind_draft(forward=True, report=add_extra_log_payload) - def _rewind_draft(self, forward: bool) -> Response: + def _rewind_draft(self, forward: bool, report: LogPayload) -> Response: try: body = CommitDraftRequest.model_validate(request.get_json(silent=True)) except PydanticValidationError as ex: @@ -930,6 +1009,7 @@ class CanvasRestApi(BaseSupersetModelRestApi): draft = RewindCanvasDraftCommand( _draft_token(), body.revision, forward=forward ).run() + report(canvas_id=draft.canvas_id) return self.response(200, result=draft_payload(draft)) @expose("/draft/commit", methods=("POST",)) @@ -939,9 +1019,10 @@ class CanvasRestApi(BaseSupersetModelRestApi): @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.commit_draft", log_to_statsd=False, + allow_extra_payload=True, ) @_handle_canvas_errors - def commit_draft(self) -> Response: + def commit_draft(self, *, add_extra_log_payload: LogPayload) -> Response: """Publish the draft named by the `X-Canvas-Draft` header. --- post: @@ -967,6 +1048,8 @@ class CanvasRestApi(BaseSupersetModelRestApi): except PydanticValidationError as ex: return self.response(400, message=_pydantic_errors(ex)) draft = load_draft(_draft_token()) + # Read before the commit, which deletes the draft. + add_extra_log_payload(canvas_id=draft.canvas_id) result = CommitCanvasDraftCommand(draft.token, body.revision).run() return self.response( 200, @@ -983,9 +1066,10 @@ class CanvasRestApi(BaseSupersetModelRestApi): @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.delete_draft", log_to_statsd=False, + allow_extra_payload=True, ) @_handle_canvas_errors - def delete_draft(self) -> Response: + def delete_draft(self, *, add_extra_log_payload: LogPayload) -> Response: """Discard the draft named by the `X-Canvas-Draft` header. --- delete: @@ -996,7 +1080,11 @@ class CanvasRestApi(BaseSupersetModelRestApi): 404: $ref: '#/components/responses/404' """ - DeleteCanvasDraftCommand(_draft_token()).run() + # Resolved before the delete, which is what makes a discarded draft + # attributable to the canvas it was abandoning. + draft = load_draft(_draft_token()) + add_extra_log_payload(canvas_id=draft.canvas_id) + DeleteCanvasDraftCommand(draft.token).run() return self.response(200, message="OK") @expose("/<id_or_uuid>/placement/<placement_id>/data", methods=("POST",)) @@ -1094,23 +1182,29 @@ class CanvasRestApi(BaseSupersetModelRestApi): request.get_json(silent=True) or {} ) except PydanticValidationError as ex: + _report_canvas_error(self, ex, 400, scope="placement_data") return self.response(400, message=_pydantic_errors(ex)) token = request.headers.get(DRAFT_TOKEN_HEADER) or None try: version = UUID(request.headers[VERSION_HEADER]) except KeyError: version = None - except ValueError: + except ValueError as ex: + _report_canvas_error(self, ex, 400, scope="placement_data") return self.response_400(message="Invalid version UUID") try: data = GetPlacementDataCommand( id_or_uuid, placement_id, body.runtime_filters, token, version ).run() - except DatasourceNotFound: + except DatasourceNotFound as ex: + _report_canvas_error(self, ex, 404, scope="placement_data") return self.response_404() - except SupersetSecurityException: + except SupersetSecurityException as ex: + _report_canvas_error(self, ex, 403, scope="placement_data") return self.response_403() except (QueryObjectValidationError, ChartDataQueryFailedError) as ex: + # A failing widget query otherwise leaves no backend trace at all. + _report_canvas_error(self, ex, 400, scope="placement_data") return self.response_400(message=str(ex.message)) dataset: dict[str, Any] = { "name": "main", diff --git a/superset/migrations/versions/2026-11-17_10-00_c4a7e9d21f08_add_canvas_id_to_logs.py b/superset/migrations/versions/2026-11-17_10-00_c4a7e9d21f08_add_canvas_id_to_logs.py new file mode 100644 index 00000000000..8ed2d9af613 --- /dev/null +++ b/superset/migrations/versions/2026-11-17_10-00_c4a7e9d21f08_add_canvas_id_to_logs.py @@ -0,0 +1,51 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +"""Add canvas_id to logs. + +The ``logs`` table carries an integer column per object kind a request can +touch, so an event can be attributed without parsing ``logs.json``. Canvas had +no such column, which left every canvas event with ``dashboard_id`` and +``slice_id`` both null and made canvas activity unqueryable. + +Nullable, no foreign key and no index, matching ``dashboard_id`` and +``slice_id`` as added in ``430039611635_log_more``. ``logs`` is append-heavy and +the queries this column exists for aggregate across all of it, so an index +would be paid for on every write without being used by the read. + +Revision ID: c4a7e9d21f08 +Revises: bf1a95a43c2d +Create Date: 2026-11-17 10:00:00.000000 + +""" + +import sqlalchemy as sa + +from superset.migrations.shared.utils import add_columns, drop_columns + +revision = "c4a7e9d21f08" +down_revision = "bf1a95a43c2d" + +TABLE = "logs" +COLUMN = "canvas_id" + + +def upgrade(): + add_columns(TABLE, sa.Column(COLUMN, sa.Integer(), nullable=True)) + + +def downgrade(): + drop_columns(TABLE, COLUMN) diff --git a/superset/models/core.py b/superset/models/core.py index a1a64fe1200..d7d1eedeb79 100755 --- a/superset/models/core.py +++ b/superset/models/core.py @@ -2218,6 +2218,7 @@ class Log(Model): # pylint: disable=too-few-public-methods user_id = Column(Integer, ForeignKey("ab_user.id")) dashboard_id = Column(Integer) slice_id = Column(Integer) + canvas_id = Column(Integer) json = Column(utils.MediumText()) user = relationship( security_manager.user_model, backref="logs", foreign_keys=[user_id] diff --git a/superset/utils/log.py b/superset/utils/log.py index e1cece42e29..082c120ae6f 100644 --- a/superset/utils/log.py +++ b/superset/utils/log.py @@ -39,14 +39,24 @@ from superset.utils.core import get_user_id, LoggerLevel, to_int logger = logging.getLogger(__name__) -# The ``logs`` table has an integer column for the dashboard or chart a request -# touched. This maps the model behind a REST API's ``datamodel`` to that column -# so every route on the matching API populates it without per-endpoint plumbing. +# The ``logs`` table has an integer column for the dashboard, chart or canvas a +# request touched. This maps the model behind a REST API's ``datamodel`` to that +# column so every route on the matching API populates it without per-endpoint +# plumbing. LOG_OBJECT_ID_COLUMNS: dict[str, str] = { "Dashboard": "dashboard_id", "Slice": "slice_id", + "Canvas": "canvas_id", } +# ``dashboard_id`` and ``slice_id`` are named parameters of +# ``AbstractEventLogger.log``, and ``slice_id`` can also be read out of +# ``form_data``, so both are resolved by hand below. Every other column in +# ``LOG_OBJECT_ID_COLUMNS`` is derived generically and travels to ``log()`` as a +# keyword argument, which keeps the abstract signature -- and so every +# downstream logger -- unchanged as columns are added. +LOG_NAMED_OBJECT_ID_COLUMNS: frozenset[str] = frozenset({"dashboard_id", "slice_id"}) + # Route parameters that identify the single object a REST API route acts on. OBJECT_ID_VIEW_ARGS: tuple[str, ...] = ( "pk", @@ -98,7 +108,8 @@ def get_object_ids_from_view_args( view: Any, view_args: dict[str, Any] ) -> dict[str, Any]: """ - Derive the ``dashboard_id`` / ``slice_id`` log fields for a REST API route. + Derive the object-id log field (``dashboard_id``, ``slice_id``, + ``canvas_id``) for a REST API route. ``view`` is the API instance the logged route was called on and ``view_args`` are the keyword arguments Flask passed to it. The result is @@ -321,6 +332,16 @@ class AbstractEventLogger(ABC): slice_id = to_int(slice_id) + # Columns beyond the two the abstract ``log()`` names. Passing them as + # keyword arguments means a logger that has never heard of them simply + # collects them in ``**kwargs``, exactly as it already does for + # ``database_id``. + extra_object_ids = { + column: to_int(payload.get(column)) + for column in LOG_OBJECT_ID_COLUMNS.values() + if column not in LOG_NAMED_OBJECT_ID_COLUMNS + } + if log_to_statsd: stats_logger_manager.instance.incr(action) @@ -341,6 +362,7 @@ class AbstractEventLogger(ABC): referrer=referrer, curated_payload=self.curate_payload(payload), curated_form_data=self.curate_form_data(form_data), + **extra_object_ids, **database_params, ) @@ -512,6 +534,7 @@ class DBEventLogger(AbstractEventLogger): records = kwargs.get("records", []) curated_payload = kwargs.get("curated_payload") + canvas_id = kwargs.get("canvas_id") # If no records but curated_payload exists, use it as a single record # This enables MCP middleware logging which passes curated_payload @@ -530,6 +553,7 @@ class DBEventLogger(AbstractEventLogger): json=json_string, dashboard_id=dashboard_id or record.get("dashboard_id"), slice_id=slice_id or record.get("slice_id"), + canvas_id=canvas_id or record.get("canvas_id"), duration_ms=duration_ms, referrer=referrer, user_id=user_id, diff --git a/superset/views/log/api.py b/superset/views/log/api.py index d4f58e8deed..279645775e3 100644 --- a/superset/views/log/api.py +++ b/superset/views/log/api.py @@ -55,6 +55,7 @@ class LogRestApi(LogMixin, BaseSupersetModelRestApi): "json", "slice_id", "dashboard_id", + "canvas_id", "duration_ms", "referrer", ] @@ -66,6 +67,7 @@ class LogRestApi(LogMixin, BaseSupersetModelRestApi): "json", "slice_id", "dashboard_id", + "canvas_id", "duration_ms", "referrer", ] diff --git a/tests/unit_tests/canvas/telemetry_test.py b/tests/unit_tests/canvas/telemetry_test.py new file mode 100644 index 00000000000..1be82154b7b --- /dev/null +++ b/tests/unit_tests/canvas/telemetry_test.py @@ -0,0 +1,202 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +"""Canvas instrumentation: error counters and canvas attribution.""" + +from __future__ import annotations + +from typing import Any +from unittest.mock import MagicMock + +import pytest +from pytest_mock import MockerFixture + +# The canvas API only exists while its feature flag is on. +pytestmark = pytest.mark.parametrize( + "app", [{"FEATURE_FLAGS": {"CANVAS": True}}], indirect=True +) + +BASE = "/api/v1/canvas" + + +def _draft(canvas_id: int = 100) -> MagicMock: + return MagicMock(token="token", canvas_id=canvas_id) # noqa: S106 + + +def _log_calls(mock_log: MagicMock, action_suffix: str) -> list[dict[str, Any]]: + """The ``log()`` keyword arguments for one action.""" + return [ + dict(call.kwargs) + for call in mock_log.call_args_list + if str( + call.args[1] if len(call.args) > 1 else call.kwargs.get("action", "") + ).endswith(action_suffix) + ] + + +def test_a_canvas_error_is_counted_and_recorded( + client: Any, full_api_access: None, mocker: MockerFixture +) -> None: + """A 404 returns silently today; it must leave a counter and a row.""" + from superset.commands.canvas.exceptions import CanvasNotFoundError + + mocker.patch("superset.canvas.api.load_draft", side_effect=CanvasNotFoundError()) + stats = mocker.patch("superset.canvas.api.stats_logger_manager") + logged = mocker.patch("superset.canvas.api.event_logger") + + response = client.get(f"{BASE}/draft", headers={"X-Canvas-Draft": "token"}) + + assert response.status_code == 404 + stats.instance.incr.assert_called_once_with("canvas.error.CanvasNotFoundError") + kwargs = logged.log_with_context.call_args.kwargs + assert kwargs["action"] == "canvas_error" + assert kwargs["error_type"] == "CanvasNotFoundError" + assert kwargs["status"] == 404 + + [email protected]( + "error_name,expected_status", + [ + ("CanvasNotFoundError", 404), + ("CanvasForbiddenError", 403), + ("CanvasDraftNotFoundError", 404), + ], +) +def test_each_error_class_gets_its_own_counter( + client: Any, + full_api_access: None, + mocker: MockerFixture, + error_name: str, + expected_status: int, +) -> None: + """The key is the exception class, so failures are distinguishable.""" + import superset.commands.canvas.exceptions as exceptions + + error = getattr(exceptions, error_name)() + mocker.patch("superset.canvas.api.load_draft", side_effect=error) + stats = mocker.patch("superset.canvas.api.stats_logger_manager") + + response = client.get(f"{BASE}/draft", headers={"X-Canvas-Draft": "token"}) + + assert response.status_code == expected_status + stats.instance.incr.assert_called_once_with(f"canvas.error.{error_name}") + + +def test_an_error_never_records_the_request_body( + client: Any, full_api_access: None, mocker: MockerFixture +) -> None: + """``include_request_data=False`` is what keeps the ops array -- and the + filter values a placement request carries -- out of ``logs.json``.""" + from superset.commands.canvas.exceptions import DraftConflictError + + mocker.patch("superset.canvas.api.load_draft", return_value=_draft()) + command = mocker.patch("superset.canvas.api.CommitCanvasDraftCommand") + command.return_value.run.side_effect = DraftConflictError(2) + logged = mocker.patch("superset.canvas.api.event_logger") + + response = client.post( + f"{BASE}/draft/commit", + json={"revision": 1}, + headers={"X-Canvas-Draft": "token"}, + ) + + assert response.status_code == 409 + kwargs = logged.log_with_context.call_args.kwargs + assert kwargs["include_request_data"] is False + # The message can quote user input, so it is deliberately not recorded. + assert "message" not in kwargs + assert set(kwargs) == { + "action", + "log_to_statsd", + "include_request_data", + "canvas_id", + "error_type", + "status", + "scope", + } + + +def test_reporting_never_masks_the_error_it_reports( + client: Any, full_api_access: None, mocker: MockerFixture +) -> None: + """Telemetry is best-effort: a broken stats backend must not turn a 404 + into a 500, nor hide the original failure from the caller.""" + from superset.commands.canvas.exceptions import CanvasNotFoundError + + mocker.patch("superset.canvas.api.load_draft", side_effect=CanvasNotFoundError()) + stats = mocker.patch("superset.canvas.api.stats_logger_manager") + stats.instance.incr.side_effect = RuntimeError("statsd is down") + + response = client.get(f"{BASE}/draft", headers={"X-Canvas-Draft": "token"}) + + assert response.status_code == 404 + + [email protected]( + "method,path,body,action", + [ + ("post", "/draft/commit", {"revision": 1}, "commit_draft"), + ("delete", "/draft", None, "delete_draft"), + ("get", "/draft", None, "get_draft"), + ], +) +def test_a_draft_route_attributes_its_canvas( + client: Any, + full_api_access: None, + mocker: MockerFixture, + method: str, + path: str, + body: dict[str, Any] | None, + action: str, +) -> None: + """A draft is named by a header, so the event logger cannot resolve the + canvas from the URL. These routes report it themselves.""" + from superset.utils.log import DBEventLogger + + mocker.patch("superset.canvas.api.load_draft", return_value=_draft(100)) + commit = mocker.patch("superset.canvas.api.CommitCanvasDraftCommand") + commit.return_value.run.return_value.revision = 2 + mocker.patch("superset.canvas.api.DeleteCanvasDraftCommand") + mocker.patch("superset.canvas.api.draft_payload", return_value={}) + mock_log = mocker.patch.object(DBEventLogger, "log") + + response = getattr(client, method)( + f"{BASE}{path}", + headers={"X-Canvas-Draft": "token"}, + **({"json": body} if body is not None else {}), + ) + + assert response.status_code == 200 + calls = _log_calls(mock_log, action) + assert calls, f"no log row for {action}" + assert calls[-1]["records"][0]["canvas_id"] == 100 + + +def test_a_draft_route_never_logs_its_token( + client: Any, full_api_access: None, mocker: MockerFixture +) -> None: + """The token travels in a header precisely so it stays out of logs.""" + from superset.utils.log import DBEventLogger + + mocker.patch("superset.canvas.api.load_draft", return_value=_draft(100)) + mocker.patch("superset.canvas.api.draft_payload", return_value={}) + mock_log = mocker.patch.object(DBEventLogger, "log") + + response = client.get(f"{BASE}/draft", headers={"X-Canvas-Draft": "s3cret-token"}) + + assert response.status_code == 200 + recorded = str(mock_log.call_args_list) + assert "s3cret-token" not in recorded diff --git a/tests/unit_tests/utils/log_tests.py b/tests/unit_tests/utils/log_tests.py index 121b26552ae..eb0a402a1cb 100644 --- a/tests/unit_tests/utils/log_tests.py +++ b/tests/unit_tests/utils/log_tests.py @@ -54,6 +54,7 @@ def test_log_from_status_info() -> None: # ``datamodel``: the helper only inspects the class name, so no ORM is needed. _Dashboard = type("Dashboard", (), {}) _Slice = type("Slice", (), {}) +_Canvas = type("Canvas", (), {}) # A model that ``logs`` has no id column for. _Database = type("Database", (), {}) @@ -71,8 +72,13 @@ def _view_for(model: type) -> SimpleNamespace: (_Dashboard, {"id_or_slug": "7"}, {"dashboard_id": 7}), (_Slice, {"pk": "3"}, {"slice_id": 3}), (_Slice, {"id_or_uuid": 3}, {"slice_id": 3}), + # canvas routes identify themselves by pk, uuid or slug + (_Canvas, {"pk": 11}, {"canvas_id": 11}), + (_Canvas, {"id_or_uuid": "11"}, {"canvas_id": 11}), + (_Canvas, {"uuid_str": "11"}, {"canvas_id": 11}), (_Dashboard, {"rison": [1, 2, 3]}, {"dashboard_ids": [1, 2, 3]}), (_Slice, {"rison": [5]}, {"slice_ids": [5]}), + (_Canvas, {"rison": [4, 6]}, {"canvas_ids": [4, 6]}), # rison payloads that are not a list of ids (list endpoints, thumbnails) (_Dashboard, {"rison": {"columns": ["id"]}}, {}), (_Dashboard, {"rison": []}, {}), @@ -148,6 +154,9 @@ def test_log_this_with_context_derives_object_id_from_route( assert payload["dashboard_id"] == 42 # ``to_int`` turns a missing id into 0; the DB logger stores that as NULL. assert not payload["slice_id"] + # ``canvas_id`` travels as a keyword argument rather than widening the + # abstract ``log()`` signature, so it is passed even on a dashboard route. + assert not payload["canvas_id"] assert payload["records"][0]["dashboard_id"] == 42 assert payload["records"][0]["pk"] == "42" @@ -183,3 +192,75 @@ def test_log_this_with_context_derives_object_id_despite_outer_decorator( payload = mock_log.call_args[1] assert payload["dashboard_id"] == 42 + + +def test_log_this_with_context_derives_canvas_id( + app_context: None, mocker: MockerFixture +) -> None: + """A canvas route fills ``canvas_id`` the way a dashboard route fills + ``dashboard_id``, with no per-endpoint plumbing.""" + mock_log = mocker.patch.object(DBEventLogger, "log") + logger = DBEventLogger() + + class FakeCanvasRestApi: # pylint: disable=too-few-public-methods + datamodel = SimpleNamespace(obj=_Canvas) + + @logger.log_this_with_context(action="CanvasRestApi.get_definition") + def get_definition(self, id_or_uuid: str) -> str: + return f"got {id_or_uuid}" + + with current_app.test_request_context("/api/v1/canvas/7/definition", method="GET"): + assert FakeCanvasRestApi().get_definition(id_or_uuid="7") == "got 7" + + payload = mock_log.call_args[1] + assert payload["canvas_id"] == 7 + assert not payload["dashboard_id"] + assert not payload["slice_id"] + + +def test_log_accepts_a_logger_that_never_heard_of_canvas( + app_context: None, +) -> None: + """Back-compat guarantee for ``EVENT_LOGGER`` subclasses. + + ``canvas_id`` is passed as a keyword argument rather than added to the + abstract ``log()`` signature, so a logger written before the column existed + keeps working untouched. If this breaks, every downstream custom logger + breaks on upgrade. + """ + from superset.utils.log import AbstractEventLogger + + seen: list[dict[str, Any]] = [] + + class LegacyEventLogger(AbstractEventLogger): + # Deliberately declares no ``canvas_id`` parameter, exactly as a + # third-party logger predating the column would not. + def log( # pylint: disable=too-many-arguments + self, + user_id: int | None, + action: str, + dashboard_id: int | None, + duration_ms: int | None, + slice_id: int | None, + referrer: str | None, + *args: Any, + **kwargs: Any, + ) -> None: + seen.append({"action": action, "kwargs": kwargs}) + + logger = LegacyEventLogger() + + class FakeCanvasRestApi: # pylint: disable=too-few-public-methods + datamodel = SimpleNamespace(obj=_Canvas) + + @logger.log_this_with_context(action="CanvasRestApi.put") + def put(self, pk: int) -> str: + return f"updated {pk}" + + with current_app.test_request_context("/api/v1/canvas/3", method="PUT"): + assert FakeCanvasRestApi().put(pk="3") == "updated 3" + + assert len(seen) == 1 + assert seen[0]["action"] == "CanvasRestApi.put" + # It lands in ``**kwargs``, which is why nothing had to change. + assert seen[0]["kwargs"]["canvas_id"] == 3
