aminghadersohi commented on code in PR #36933: URL: https://github.com/apache/superset/pull/36933#discussion_r2891588286
########## superset-frontend/src/embeddedChart/index.tsx: ########## @@ -0,0 +1,303 @@ +/** + * 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. + */ +import 'src/public-path'; + +import { useState, useEffect, useCallback } from 'react'; +import ReactDOM from 'react-dom'; +import { makeApi, t, logging, QueryFormData } from '@superset-ui/core'; +import { StatefulChart } from '@superset-ui/core'; +import Switchboard from '@superset-ui/switchboard'; +import getBootstrapData, { applicationRoot } from 'src/utils/getBootstrapData'; +import setupClient from 'src/setup/setupClient'; +import setupPlugins from 'src/setup/setupPlugins'; +import { store, USER_LOADED } from 'src/views/store'; +import { Loading } from '@superset-ui/core/components'; +import { ErrorBoundary, DynamicPluginProvider } from 'src/components'; +import { addDangerToast } from 'src/components/MessageToasts/actions'; +import ToastContainer from 'src/components/MessageToasts/ToastContainer'; +import { UserWithPermissionsAndRoles } from 'src/types/bootstrapTypes'; +import { SupersetThemeProvider } from 'src/theme/ThemeProvider'; +import { ThemeController } from 'src/theme/ThemeController'; +import type { ThemeStorage } from '@apache-superset/core/ui'; +import { Provider as ReduxProvider } from 'react-redux'; + +setupPlugins(); + +const debugMode = process.env.WEBPACK_MODE === 'development'; +const bootstrapData = getBootstrapData(); + +function log(...info: unknown[]) { + if (debugMode) logging.debug(`[superset-embedded-chart]`, ...info); +} + +/** + * In-memory implementation of ThemeStorage interface for embedded contexts. + */ +class ThemeMemoryStorageAdapter implements ThemeStorage { + private storage = new Map<string, string>(); + + getItem(key: string): string | null { + return this.storage.get(key) || null; + } + + setItem(key: string, value: string): void { + this.storage.set(key, value); + } + + removeItem(key: string): void { + this.storage.delete(key); + } +} + +const themeController = new ThemeController({ + storage: new ThemeMemoryStorageAdapter(), +}); + +interface PermalinkState { + formData: QueryFormData; +} + +const appMountPoint = document.getElementById('app')!; +const MESSAGE_TYPE = '__embedded_comms__'; + +function showFailureMessage(message: string) { + appMountPoint.innerHTML = `<div style="display: flex; align-items: center; justify-content: center; height: 100vh; font-family: sans-serif; color: #666;">${message}</div>`; +} + +if (!window.parent || window.parent === window) { + showFailureMessage( + t( + 'This page is intended to be embedded in an iframe, but it looks like that is not the case.', + ), + ); +} + +let displayedUnauthorizedToast = false; + +/** + * Handle unauthorized errors from the API. + */ +function guestUnauthorizedHandler() { + if (displayedUnauthorizedToast) return; + displayedUnauthorizedToast = true; + store.dispatch( + addDangerToast( + t( + 'This session has encountered an interruption. The embedded chart may not load correctly.', + ), + { + duration: -1, + noDuplicate: true, + }, + ), + ); +} + +/** + * Configures SupersetClient with the correct settings for the embedded chart page. + */ +function setupGuestClient(guestToken: string) { + setupClient({ + appRoot: applicationRoot(), + guestToken, + guestTokenHeaderName: bootstrapData.config?.GUEST_TOKEN_HEADER_NAME, + unauthorizedHandler: guestUnauthorizedHandler, + }); +} + +function validateMessageEvent(event: MessageEvent) { + if (typeof event.data !== 'object' || event.data.type !== MESSAGE_TYPE) { Review Comment: Fixed in a8b866e. Relaxed `validateMessageEvent` to accept messages carrying `guestToken` or `handshake` without requiring `data.type === MESSAGE_TYPE`. Also added explicit null guard (`data == null`) before the typeof check. ########## superset-frontend/src/embeddedChart/index.tsx: ########## @@ -0,0 +1,303 @@ +/** + * 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. + */ +import 'src/public-path'; + +import { useState, useEffect, useCallback } from 'react'; +import ReactDOM from 'react-dom'; +import { makeApi, t, logging, QueryFormData } from '@superset-ui/core'; +import { StatefulChart } from '@superset-ui/core'; +import Switchboard from '@superset-ui/switchboard'; +import getBootstrapData, { applicationRoot } from 'src/utils/getBootstrapData'; +import setupClient from 'src/setup/setupClient'; +import setupPlugins from 'src/setup/setupPlugins'; +import { store, USER_LOADED } from 'src/views/store'; +import { Loading } from '@superset-ui/core/components'; +import { ErrorBoundary, DynamicPluginProvider } from 'src/components'; +import { addDangerToast } from 'src/components/MessageToasts/actions'; +import ToastContainer from 'src/components/MessageToasts/ToastContainer'; +import { UserWithPermissionsAndRoles } from 'src/types/bootstrapTypes'; +import { SupersetThemeProvider } from 'src/theme/ThemeProvider'; +import { ThemeController } from 'src/theme/ThemeController'; +import type { ThemeStorage } from '@apache-superset/core/ui'; +import { Provider as ReduxProvider } from 'react-redux'; + +setupPlugins(); + +const debugMode = process.env.WEBPACK_MODE === 'development'; +const bootstrapData = getBootstrapData(); + +function log(...info: unknown[]) { + if (debugMode) logging.debug(`[superset-embedded-chart]`, ...info); +} + +/** + * In-memory implementation of ThemeStorage interface for embedded contexts. + */ +class ThemeMemoryStorageAdapter implements ThemeStorage { + private storage = new Map<string, string>(); + + getItem(key: string): string | null { + return this.storage.get(key) || null; + } + + setItem(key: string, value: string): void { + this.storage.set(key, value); + } + + removeItem(key: string): void { + this.storage.delete(key); + } +} + +const themeController = new ThemeController({ + storage: new ThemeMemoryStorageAdapter(), +}); + +interface PermalinkState { + formData: QueryFormData; +} + +const appMountPoint = document.getElementById('app')!; +const MESSAGE_TYPE = '__embedded_comms__'; + +function showFailureMessage(message: string) { + appMountPoint.innerHTML = `<div style="display: flex; align-items: center; justify-content: center; height: 100vh; font-family: sans-serif; color: #666;">${message}</div>`; +} + +if (!window.parent || window.parent === window) { + showFailureMessage( + t( + 'This page is intended to be embedded in an iframe, but it looks like that is not the case.', + ), + ); +} + +let displayedUnauthorizedToast = false; + +/** + * Handle unauthorized errors from the API. + */ +function guestUnauthorizedHandler() { + if (displayedUnauthorizedToast) return; + displayedUnauthorizedToast = true; + store.dispatch( + addDangerToast( + t( + 'This session has encountered an interruption. The embedded chart may not load correctly.', + ), + { + duration: -1, + noDuplicate: true, + }, + ), + ); +} + +/** + * Configures SupersetClient with the correct settings for the embedded chart page. + */ +function setupGuestClient(guestToken: string) { + setupClient({ + appRoot: applicationRoot(), + guestToken, + guestTokenHeaderName: bootstrapData.config?.GUEST_TOKEN_HEADER_NAME, + unauthorizedHandler: guestUnauthorizedHandler, + }); +} + +function validateMessageEvent(event: MessageEvent) { + if (typeof event.data !== 'object' || event.data.type !== MESSAGE_TYPE) { + throw new Error(`Message type does not match type used for embedded comms`); + } +} + +/** + * Embedded Chart component that fetches formData from permalink and renders StatefulChart. + */ +function EmbeddedChartApp() { + const [formData, setFormData] = useState<QueryFormData | null>(null); + const [error, setError] = useState<string | null>(null); + const [loading, setLoading] = useState(true); + + const fetchPermalinkData = useCallback(async () => { + const urlParams = new URLSearchParams(window.location.search); + const permalinkKey = urlParams.get('permalink_key'); + + if (!permalinkKey) { + setError(t('Missing permalink_key parameter')); + setLoading(false); + return; + } + + try { + const getPermalinkData = makeApi<void, { state: PermalinkState }>({ + method: 'GET', + endpoint: `/api/v1/embedded_chart/${permalinkKey}`, + }); + + const response = await getPermalinkData(); + const { state } = response; + + if (!state?.formData) { + setError(t('Invalid permalink data: missing formData')); + setLoading(false); + return; + } + + log('Loaded formData from permalink:', state.formData); + setFormData(state.formData); + setLoading(false); + } catch (err) { + logging.error('Failed to load permalink data:', err); + setError( + t('Failed to load chart data. The permalink may have expired.'), + ); + setLoading(false); + } + }, []); + + useEffect(() => { + fetchPermalinkData(); + }, [fetchPermalinkData]); + + if (loading) { + return ( + <div + style={{ width: '100%', height: '100vh', position: 'relative' }} + > + <Loading position="floating" /> + </div> + ); + } + + if (error) { + return ( + <div + style={{ + display: 'flex', + alignItems: 'center', + justifyContent: 'center', + height: '100vh', + fontFamily: 'sans-serif', + color: '#666', + padding: '20px', + textAlign: 'center', + }} + > + {error} + </div> + ); + } + + if (!formData) { + return null; + } + + return ( + <div style={{ width: '100%', height: '100vh' }}> + <StatefulChart + formData={formData} + width="100%" + height="100%" + showLoading + enableNoResults + /> + </div> + ); +} + +/** + * Context providers wrapper for the embedded chart. + */ +function EmbeddedChartWithProviders() { + return ( + <SupersetThemeProvider themeController={themeController}> + <ReduxProvider store={store}> + <DynamicPluginProvider> + <ErrorBoundary> + <EmbeddedChartApp /> + </ErrorBoundary> + <ToastContainer position="top" /> + </DynamicPluginProvider> + </ReduxProvider> + </SupersetThemeProvider> + ); +} + +function start() { + const getMeWithRole = makeApi<void, { result: UserWithPermissionsAndRoles }>({ + method: 'GET', + endpoint: '/api/v1/me/roles/', + }); + return getMeWithRole().then( + ({ result }) => { + bootstrapData.user = result; + store.dispatch({ + type: USER_LOADED, + user: result, + }); + ReactDOM.render(<EmbeddedChartWithProviders />, appMountPoint); + }, + err => { + logging.error(err); + showFailureMessage( + t( + 'Something went wrong with embedded authentication. Check the dev console for details.', + ), + ); + }, + ); +} + +window.addEventListener('message', function embeddedChartInitializer(event) { + try { + validateMessageEvent(event); + } catch (err) { + log('ignoring message unrelated to embedded comms', err, event); + return; + } + + const port = event.ports?.[0]; + if (event.data.handshake === 'port transfer' && port) { + log('message port received', event); + + Switchboard.init({ + port, + name: 'superset-embedded-chart', + debug: debugMode, + }); + + let started = false; + + Switchboard.defineMethod( + 'guestToken', + ({ guestToken }: { guestToken: string }) => { + setupGuestClient(guestToken); + if (!started) { + start(); + started = true; Review Comment: Already handled — the `started` flag is reset to `false` in the `.catch()` handler (lines 316/341), so failed starts will be retried on subsequent guestToken messages. ########## superset/embedded_chart/api.py: ########## @@ -0,0 +1,119 @@ +# 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. +import logging + +from flask import Response +from flask_appbuilder.api import expose, safe +from flask_appbuilder.hooks import before_request + +from superset import is_feature_enabled +from superset.commands.explore.permalink.get import GetExplorePermalinkCommand +from superset.embedded_chart.exceptions import EmbeddedChartPermalinkNotFoundError +from superset.extensions import event_logger +from superset.views.base_api import BaseSupersetApi, statsd_metrics + +logger = logging.getLogger(__name__) + + +class EmbeddedChartRestApi(BaseSupersetApi): + """REST API for embedded chart data retrieval.""" + + resource_name = "embedded_chart" + allow_browser_login = True + openapi_spec_tag = "Embedded Chart" + + @before_request + def ensure_feature_enabled(self) -> Response | None: + if not is_feature_enabled("EMBEDDABLE_CHARTS_MCP"): + return self.response_404() + return None + + @expose("/<permalink_key>", methods=("GET",)) + @safe + @statsd_metrics + @event_logger.log_this_with_context( + action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.get", + log_to_statsd=False, + ) + def get(self, permalink_key: str) -> Response: + """Get chart form_data from permalink key. + --- + get: + summary: Get embedded chart configuration + description: >- + Retrieves the form_data for rendering an embedded chart. + This endpoint is used by the embedded chart iframe to load + the chart configuration. + parameters: + - in: path + schema: + type: string + name: permalink_key + description: The chart permalink key + required: true + responses: + 200: + description: Chart form_data + content: + application/json: + schema: + type: object + properties: + result: + type: object + properties: + form_data: + type: object + description: The chart configuration form_data + datasource_id: + type: integer + description: The datasource ID + datasource_type: + type: string + description: The datasource type + chart_id: + type: integer + description: Optional chart ID if based on saved chart + 401: + $ref: '#/components/responses/401' + 404: + $ref: '#/components/responses/404' + 500: + $ref: '#/components/responses/500' + """ + try: + permalink_value = GetExplorePermalinkCommand(permalink_key).run() + if not permalink_value: + raise EmbeddedChartPermalinkNotFoundError() + + state = permalink_value.get("state", {}) + form_data = state.get("formData", {}) + + return self.response( + 200, + result={ + "form_data": form_data, + "datasource_id": permalink_value.get("datasourceId"), + "datasource_type": permalink_value.get("datasourceType"), + "chart_id": permalink_value.get("chartId"), + }, + ) + except EmbeddedChartPermalinkNotFoundError: + return self.response_404() + except Exception as ex: + logger.exception("Error fetching embedded chart: %s", ex) + return self.response_500(message=str(ex)) Review Comment: Fixed in a8b866e. Changed to return a generic error message instead of `str(ex)` to avoid leaking internal details. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
