Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 65 additions & 42 deletions superset/commands/chart/warm_up_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
# under the License.


from typing import Any, Optional, Union
from typing import Any, cast, Optional, Union

from flask import g

Expand All @@ -26,10 +26,11 @@
ChartInvalidError,
WarmUpCacheChartNotFoundError,
)
from superset.common.db_query_status import QueryStatus
from superset.extensions import db
from superset.models.slice import Slice
from superset.utils import json
from superset.utils.core import error_msg_from_exception
from superset.utils.core import error_msg_from_exception, QueryObjectFilterClause
from superset.views.utils import get_dashboard_extra_filters, get_form_data, get_viz
from superset.viz import viz_types

Expand All @@ -45,54 +46,76 @@ def __init__(
self._dashboard_id = dashboard_id
self._extra_filters = extra_filters

def _get_dashboard_filters(self, chart_id: int) -> list[dict[str, Any]]:
"""Retrieve dashboard filters from extra_filters or dashboard metadata."""
if not self._dashboard_id:
return []

if self._extra_filters:
return json.loads(self._extra_filters)

return get_dashboard_extra_filters(chart_id, self._dashboard_id)

def _warm_up_legacy_cache(
self, chart: Slice, form_data: dict[str, Any]
) -> tuple[Any, Any]:
"""Warm up cache for legacy visualizations."""
if not chart.datasource:
raise ChartInvalidError("Chart's datasource does not exist")

if self._dashboard_id:
form_data["extra_filters"] = self._get_dashboard_filters(chart.id)

g.form_data = form_data
payload = get_viz(
datasource_type=chart.datasource.type,
datasource_id=chart.datasource.id,
form_data=form_data,
force=True,
).get_payload()
delattr(g, "form_data")

return payload["errors"] or None, payload["status"]

def _warm_up_non_legacy_cache(self, chart: Slice) -> tuple[Any, Any]:
"""Warm up cache for non-legacy visualizations."""
query_context = chart.get_query_context()

if not query_context:
raise ChartInvalidError("Chart's query context does not exist")

# Apply dashboard filters if dashboard_id is provided
if dashboard_filters := self._get_dashboard_filters(chart.id):
for query in query_context.queries:
query.filter.extend(
cast(list[QueryObjectFilterClause], dashboard_filters)
)

query_context.force = True
command = ChartDataCommand(query_context)
command.validate()
payload = command.run()

# Report the first error.
for query_result in cast(list[dict[str, Any]], payload["queries"]):
error = query_result.get("error")
status = query_result.get("status")
if error is not None:
return error, status

return None, QueryStatus.SUCCESS

def run(self) -> dict[str, Any]:
self.validate()
chart: Slice = self._chart_or_id # type: ignore
chart = cast(Slice, self._chart_or_id)

try:
form_data = get_form_data(chart.id, use_slice_data=True)[0]

if form_data.get("viz_type") in viz_types:
# Legacy visualizations.
if not chart.datasource:
raise ChartInvalidError("Chart's datasource does not exist")

if self._dashboard_id:
form_data["extra_filters"] = (
json.loads(self._extra_filters)
if self._extra_filters
else get_dashboard_extra_filters(chart.id, self._dashboard_id)
)

g.form_data = form_data
payload = get_viz(
datasource_type=chart.datasource.type,
datasource_id=chart.datasource.id,
form_data=form_data,
force=True,
).get_payload()
delattr(g, "form_data")
error = payload["errors"] or None
status = payload["status"]
error, status = self._warm_up_legacy_cache(chart, form_data)
else:
# Non-legacy visualizations.
query_context = chart.get_query_context()

if not query_context:
raise ChartInvalidError("Chart's query context does not exist")

query_context.force = True
command = ChartDataCommand(query_context)
command.validate()
payload = command.run()

# Report the first error.
for query in payload["queries"]:
error = query["error"]
status = query["status"]

if error is not None:
break
error, status = self._warm_up_non_legacy_cache(chart)
except Exception as ex: # pylint: disable=broad-except
error = error_msg_from_exception(ex)
status = None
Expand Down
16 changes: 16 additions & 0 deletions tests/unit_tests/commands/chart/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# 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.
Loading
Loading