Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor!: add possibility to deploy under the URI prefix #26320

Draft
wants to merge 6 commits into
base: master
Choose a base branch
from
Draft
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
1 change: 1 addition & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ RUN --mount=type=bind,target=./package.json,src=./superset-frontend/package.json

COPY ./superset-frontend ./
# This seems to be the most expensive step
ARG ASSET_BASE_URL=""
RUN npm run ${BUILD_CMD}

######################################################################
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ function prepareDashboardFilters(
cy.createSampleDashboards([0]);
cy.request({
method: 'GET',
url: `api/v1/dashboard/1-sample-dashboard`,
url: `/api/v1/dashboard/1-sample-dashboard`,
}).then(res => {
const { body } = res;
const dashboardId = body.result.id;
Expand Down Expand Up @@ -170,7 +170,7 @@ function prepareDashboardFilters(
return cy
.request({
method: 'PUT',
url: `api/v1/dashboard/${dashboardId}`,
url: `/api/v1/dashboard/${dashboardId}`,
body: {
json_metadata: JSON.stringify(jsonMetadata),
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ describe('SqlLab query panel', () => {
});

it.skip('successfully saves a query', () => {
cy.intercept('api/v1/database/**/tables/**').as('getTables');
cy.intercept('/api/v1/database/**/tables/**').as('getTables');
cy.intercept('savedqueryviewapi/**').as('getSavedQuery');

const query =
Expand Down
2 changes: 1 addition & 1 deletion superset-frontend/cypress-base/cypress/support/e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ Cypress.Commands.add(
const accessToken = window.localStorage.getItem('access_token');
cy.request({
method: 'POST',
url: 'api/v1/explore/form_data',
url: '/api/v1/explore/form_data',
body: {
datasource_id,
datasource_type,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ export default class SupersetClientClass {
method: 'GET',
mode: this.mode,
timeout: this.timeout,
url: this.getUrl({ endpoint: 'api/v1/security/csrf_token/' }),
url: this.getUrl({ endpoint: '/api/v1/security/csrf_token/' }),
parseMethod: 'json',
}).then(({ json }) => {
if (typeof json === 'object') {
Expand Down Expand Up @@ -270,9 +270,9 @@ export default class SupersetClientClass {

const host = inputHost ?? this.host;
const cleanHost = host.slice(-1) === '/' ? host.slice(0, -1) : host; // no backslash

const prefixedEndpoint = `${DEFAULT_BASE_URL}${endpoint}`;
return `${this.protocol}//${cleanHost}/${
endpoint[0] === '/' ? endpoint.slice(1) : endpoint
prefixedEndpoint[0] === '/' ? prefixedEndpoint.slice(1) : prefixedEndpoint
}`;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@

import { FetchRetryOptions } from './types';

export const DEFAULT_BASE_URL = 'http://localhost';
export const DEFAULT_BASE_URL =
// eslint-disable-next-line no-underscore-dangle
(window as any).__SUPERSET_DEPLOYMENT_PREFIX__ ?? '';

// HTTP status codes
export const HTTP_STATUS_OK = 200;
Expand Down
3 changes: 2 additions & 1 deletion superset-frontend/src/SqlLab/components/App/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
LOG_ACTIONS_SQLLAB_WARN_LOCAL_STORAGE_USAGE,
LOG_ACTIONS_SQLLAB_MONITOR_LOCAL_STORAGE_USAGE,
} from 'src/logger/LogUtils';
import { withPrefix } from 'src/utils/routeUtils';
import TabbedSqlEditors from '../TabbedSqlEditors';
import QueryAutoRefresh from '../QueryAutoRefresh';

Expand Down Expand Up @@ -189,7 +190,7 @@ class App extends React.PureComponent {
return (
<Redirect
to={{
pathname: '/sqllab/history/',
pathname: withPrefix('/sqllab/history/'),
replace: true,
}}
/>
Expand Down
4 changes: 2 additions & 2 deletions superset-frontend/src/SqlLab/components/QueryTable/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import { Tooltip } from 'src/components/Tooltip';
import { SqlLabRootState } from 'src/SqlLab/types';
import ModalTrigger from 'src/components/ModalTrigger';
import { UserWithPermissionsAndRoles as User } from 'src/types/bootstrapTypes';
import { withPrefix } from 'src/utils/routeUtils';
import ResultSet from '../ResultSet';
import HighlightedSql from '../HighlightedSql';
import { StaticPosition, verticalAlign, StyledTooltip } from './styles';
Expand All @@ -61,8 +62,7 @@ interface QueryTableProps {
}

const openQuery = (id: number) => {
const url = `/sqllab?queryId=${id}`;
window.open(url);
window.open(withPrefix(`/sqllab/?queryId=${id}`));
};

const QueryTable = ({
Expand Down
3 changes: 2 additions & 1 deletion superset-frontend/src/SqlLab/components/ResultSet/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ import {
} from 'src/SqlLab/actions/sqlLab';
import { URL_PARAMS } from 'src/constants';
import Icons from 'src/components/Icons';
import { withPrefix } from 'src/utils/routeUtils';
import ExploreCtasResultsButton from '../ExploreCtasResultsButton';
import ExploreResultsButton from '../ExploreResultsButton';
import HighlightedSql from '../HighlightedSql';
Expand Down Expand Up @@ -272,7 +273,7 @@ const ResultSet = ({
};

const getExportCsvUrl = (clientId: string) =>
`/api/v1/sqllab/export/${clientId}/`;
withPrefix(`/api/v1/sqllab/export/${clientId}/`);

const renderControls = () => {
if (search || visualize || csv) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,17 +110,17 @@ describe('TabbedSqlEditors', () => {
it('should handle id', async () => {
uriStub.returns({ id: 1 });
await mountWithAct();
expect(window.history.replaceState.getCall(0).args[2]).toBe('/sqllab');
expect(window.history.replaceState.getCall(0).args[2]).toBe('/sqllab/');
});
it('should handle savedQueryId', async () => {
uriStub.returns({ savedQueryId: 1 });
await mountWithAct();
expect(window.history.replaceState.getCall(0).args[2]).toBe('/sqllab');
expect(window.history.replaceState.getCall(0).args[2]).toBe('/sqllab/');
});
it('should handle sql', async () => {
uriStub.returns({ sql: 1, dbid: 1 });
await mountWithAct();
expect(window.history.replaceState.getCall(0).args[2]).toBe('/sqllab');
expect(window.history.replaceState.getCall(0).args[2]).toBe('/sqllab/');
});
it('should handle custom url params', async () => {
uriStub.returns({
Expand All @@ -131,7 +131,7 @@ describe('TabbedSqlEditors', () => {
});
await mountWithAct();
expect(window.history.replaceState.getCall(0).args[2]).toBe(
'/sqllab?custom_value=str&extra_attr1=true',
'/sqllab/?custom_value=str&extra_attr1=true',
);
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import * as Actions from 'src/SqlLab/actions/sqlLab';
import { EmptyStateBig } from 'src/components/EmptyState';
import getBootstrapData from 'src/utils/getBootstrapData';
import { locationContext } from 'src/pages/SqlLab/LocationContext';
import { withPrefix } from 'src/utils/routeUtils';
import SqlEditor from '../SqlEditor';
import SqlEditorTabHeader from '../SqlEditorTabHeader';

Expand Down Expand Up @@ -76,7 +77,7 @@ const userOS = detectOS();
class TabbedSqlEditors extends React.PureComponent {
constructor(props) {
super(props);
const sqlLabUrl = '/sqllab';
const sqlLabUrl = withPrefix('/sqllab/');
this.state = {
sqlLabUrl,
};
Expand Down
2 changes: 1 addition & 1 deletion superset-frontend/src/assets/staticPages/404.html
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ <h1>Page not found</h1>
Sorry, we cannot find the page you are looking for. You may have
mistyped the address or the page may have moved.
</p>
<a href="/" class="button">Back to home</a>
<a href="<%= prefix %>/" class="button">Back to home</a>
</section>
<img
alt="404"
Expand Down
2 changes: 1 addition & 1 deletion superset-frontend/src/assets/staticPages/500.html
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ <h1>Internal server error</h1>
Sorry, something went wrong. We are fixing the mistake now. Try again
later or go back to home.
</p>
<a href="/" class="button">Back to home</a>
<a href="<%= prefix %>/" class="button">Back to home</a>
</section>
<img
alt="500"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import Button from 'src/components/Button';
import { useSelector } from 'react-redux';
import { DashboardPageIdContext } from 'src/dashboard/containers/DashboardPage';
import { Slice } from 'src/types/Chart';
import { withPrefix } from 'src/utils/routeUtils';
import DrillDetailPane from './DrillDetailPane';

interface ModalFooterProps {
Expand Down Expand Up @@ -78,7 +79,10 @@ export default function DrillDetailModal({
);

const exploreUrl = useMemo(
() => `/explore/?dashboard_page_id=${dashboardPageId}&slice_id=${chartId}`,
() =>
withPrefix(
`/explore/?dashboard_page_id=${dashboardPageId}&slice_id=${chartId}`,
),
[chartId, dashboardPageId],
);

Expand Down
4 changes: 3 additions & 1 deletion superset-frontend/src/components/Chart/chartAction.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ import { updateDataMask } from 'src/dataMask/actions';
import { waitForAsyncData } from 'src/middleware/asyncEvent';
import { safeStringify } from 'src/utils/safeStringify';

import { withPrefix } from 'src/utils/routeUtils';

export const CHART_UPDATE_STARTED = 'CHART_UPDATE_STARTED';
export function chartUpdateStarted(queryController, latestQueryFormData, key) {
return {
Expand Down Expand Up @@ -578,7 +580,7 @@ export function redirectSQLLab(formData, history) {
return dispatch => {
getChartDataRequest({ formData, resultFormat: 'json', resultType: 'query' })
.then(({ json }) => {
const redirectUrl = '/sqllab/';
const redirectUrl = withPrefix('/sqllab/');
const payload = {
datasourceKey: formData.datasource,
sql: json.result[0].query,
Expand Down
8 changes: 6 additions & 2 deletions superset-frontend/src/components/EmptyState/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ import { styled, css, SupersetTheme, t } from '@superset-ui/core';
import { Empty } from 'src/components';
import Button from 'src/components/Button';

import { withPrefix } from 'src/utils/routeUtils';

export enum EmptyStateSize {
Small,
Medium,
Expand Down Expand Up @@ -119,7 +121,9 @@ const ActionButton = styled(Button)`
`;

const getImage = (image: string | ReactNode) =>
typeof image === 'string' ? `/static/assets/images/${image}` : image;
typeof image === 'string'
? withPrefix(`/static/assets/images/${image}`)
: image;

const getImageHeight = (size: EmptyStateSize) => {
switch (size) {
Expand Down Expand Up @@ -242,7 +246,7 @@ export const emptyStateComponent = (emptyResultsWithSearch: boolean) => (
description={
<p>
{TRANSLATIONS.MANAGE_YOUR_DATABASES_TEXT}{' '}
<a href="/databaseview/list">{TRANSLATIONS.HERE_TEXT}</a>
<a href={withPrefix('/databaseview/list')}>{TRANSLATIONS.HERE_TEXT}</a>
</p>
}
/>
Expand Down
19 changes: 13 additions & 6 deletions superset-frontend/src/components/GenericLink/GenericLink.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,26 @@

import React from 'react';
import { render, screen } from 'spec/helpers/testing-library';
import { withPrefix } from 'src/utils/routeUtils';
import { GenericLink } from './GenericLink';

test('renders', () => {
render(<GenericLink to="/explore">Link to Explore</GenericLink>, {
useRouter: true,
});
render(
<GenericLink to={withPrefix('/explore')}>Link to Explore</GenericLink>,
{
useRouter: true,
},
);
expect(screen.getByText('Link to Explore')).toBeVisible();
});

test('navigates to internal URL', () => {
render(<GenericLink to="/explore">Link to Explore</GenericLink>, {
useRouter: true,
});
render(
<GenericLink to={withPrefix('/explore')}>Link to Explore</GenericLink>,
{
useRouter: true,
},
);
const internalLink = screen.getByTestId('internal-link');
expect(internalLink).toHaveAttribute('href', '/explore');
});
Expand Down
3 changes: 2 additions & 1 deletion superset-frontend/src/components/ListView/CrossLinks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import React, { useMemo, useRef } from 'react';
import { styled, useTruncation } from '@superset-ui/core';
import { Link } from 'react-router-dom';
import { withPrefix } from 'src/utils/routeUtils';
import CrossLinksTooltip from './CrossLinksTooltip';

export type CrossLinkProps = {
Expand Down Expand Up @@ -63,7 +64,7 @@ const StyledCrossLinks = styled.div`
export default function CrossLinks({
crossLinks,
maxLinks = 20,
linkPrefix = '/superset/dashboard/',
linkPrefix = withPrefix('/superset/dashboard/'),
}: CrossLinksProps) {
const crossLinksRef = useRef<HTMLDivElement>(null);
const plusRef = useRef<HTMLDivElement>(null);
Expand Down
4 changes: 3 additions & 1 deletion superset-frontend/src/components/Tags/Tag.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import AntdTag from 'antd/lib/tag';
import React, { useMemo } from 'react';
import { Tooltip } from 'src/components/Tooltip';

import { withPrefix } from 'src/utils/routeUtils';

const StyledTag = styled(AntdTag)`
${({ theme }) => `
margin-top: ${theme.gridUnit}px;
Expand Down Expand Up @@ -65,7 +67,7 @@ const Tag = ({
<StyledTag data-test="tag" role="link" key={id} onClick={onClick}>
{id ? (
<a
href={`/superset/all_entities/?id=${id}`}
href={withPrefix(`/superset/all_entities/?id=${id}`)}
target="_blank"
rel="noreferrer"
>
Expand Down
3 changes: 2 additions & 1 deletion superset-frontend/src/dashboard/actions/dashboardState.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ import { getActiveFilters } from 'src/dashboard/util/activeDashboardFilters';
import { safeStringify } from 'src/utils/safeStringify';
import { logEvent } from 'src/logger/actions';
import { LOG_ACTIONS_CONFIRM_OVERWRITE_DASHBOARD_METADATA } from 'src/logger/LogUtils';
import { withPrefix } from 'src/utils/routeUtils';
import { UPDATE_COMPONENTS_PARENTS_LIST } from './dashboardLayout';
import {
saveChartConfiguration,
Expand Down Expand Up @@ -346,7 +347,7 @@ export function saveDashboardRequest(data, id, saveType) {
window.history.pushState(
{ event: 'dashboard_properties_changed' },
'',
`/superset/dashboard/${slug || id}/`,
withPrefix(`/superset/dashboard/${slug || id}/`),
);

dispatch(addSuccessToast(t('This dashboard was saved successfully.')));
Expand Down
1 change: 1 addition & 0 deletions superset-frontend/src/dashboard/actions/hydrate.js
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,7 @@ export const hydrateDashboard =
'Superset',
roles,
),
chart_can_edit: findPermission('can_write', 'Chart', roles),
superset_can_explore: findPermission(
'can_explore',
'Superset',
Expand Down
5 changes: 3 additions & 2 deletions superset-frontend/src/dashboard/components/DashboardGrid.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import React from 'react';
import PropTypes from 'prop-types';
import { addAlpha, css, styled, t } from '@superset-ui/core';
import { EmptyStateBig } from 'src/components/EmptyState';
import { withPrefix } from 'src/utils/routeUtils';
import { componentShape } from '../util/propShapes';
import DashboardComponent from '../containers/DashboardComponent';
import DragDroppable from './dnd/DragDroppable';
Expand Down Expand Up @@ -203,7 +204,7 @@ class DashboardGrid extends React.PureComponent {
}
buttonAction={() => {
window.open(
`/chart/add?dashboard_id=${dashboardId}`,
withPrefix(`/chart/add/?dashboard_id=${dashboardId}`),
'_blank',
'noopener noreferrer',
);
Expand All @@ -226,7 +227,7 @@ class DashboardGrid extends React.PureComponent {
}
buttonAction={() => {
window.open(
`/chart/add?dashboard_id=${dashboardId}`,
withPrefix(`/chart/add/?dashboard_id=${dashboardId}`),
'_blank',
'noopener noreferrer',
);
Expand Down
6 changes: 5 additions & 1 deletion superset-frontend/src/dashboard/components/SaveModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ import {
SAVE_TYPE_NEWDASHBOARD,
} from 'src/dashboard/util/constants';

import { withPrefix } from 'src/utils/routeUtils';

type SaveType = typeof SAVE_TYPE_OVERWRITE | typeof SAVE_TYPE_NEWDASHBOARD;

type SaveModalProps = {
Expand Down Expand Up @@ -154,7 +156,9 @@ class SaveModal extends React.PureComponent<SaveModalProps, SaveModalState> {
} else {
this.onSave(data, dashboardId, saveType).then((resp: JsonResponse) => {
if (saveType === SAVE_TYPE_NEWDASHBOARD && resp.json?.result?.id) {
window.location.href = `/superset/dashboard/${resp.json.result.id}/`;
window.location.href = withPrefix(
`/superset/dashboard/${resp.json.result.id}/`,
);
}
});
this.modal?.current?.close?.();
Expand Down
Loading