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

chore: Removes no-use-before-define warnings #20298

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
114 changes: 57 additions & 57 deletions superset-frontend/packages/superset-ui-switchboard/src/switchboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,63 @@ export type Params = {
debug?: boolean;
};

// Each message we send on the channel specifies an action we want the other side to cooperate with.
enum Actions {
GET = 'get',
REPLY = 'reply',
EMIT = 'emit',
ERROR = 'error',
}

type Method<A extends {}, R> = (args: A) => R | Promise<R>;

// helper types/functions for making sure wires don't get crossed

interface Message {
switchboardAction: Actions;
}

interface GetMessage<T = any> extends Message {
switchboardAction: Actions.GET;
method: string;
messageId: string;
args: T;
}

function isGet(message: Message): message is GetMessage {
return message.switchboardAction === Actions.GET;
}

interface ReplyMessage<T = any> extends Message {
switchboardAction: Actions.REPLY;
messageId: string;
result: T;
}

function isReply(message: Message): message is ReplyMessage {
return message.switchboardAction === Actions.REPLY;
}

interface EmitMessage<T = any> extends Message {
switchboardAction: Actions.EMIT;
method: string;
args: T;
}

function isEmit(message: Message): message is EmitMessage {
return message.switchboardAction === Actions.EMIT;
}

interface ErrorMessage extends Message {
switchboardAction: Actions.ERROR;
messageId: string;
error: string;
}

function isError(message: Message): message is ErrorMessage {
return message.switchboardAction === Actions.ERROR;
}

/**
* A utility for communications between an iframe and its parent, used by the Superset embedded SDK.
* This builds useful patterns on top of the basic functionality offered by MessageChannel.
Expand Down Expand Up @@ -185,60 +242,3 @@ export class Switchboard {
return `m_${this.name}_${this.incrementor++}`;
}
}

type Method<A extends {}, R> = (args: A) => R | Promise<R>;

// Each message we send on the channel specifies an action we want the other side to cooperate with.
enum Actions {
GET = 'get',
REPLY = 'reply',
EMIT = 'emit',
ERROR = 'error',
}

// helper types/functions for making sure wires don't get crossed

interface Message {
switchboardAction: Actions;
}

interface GetMessage<T = any> extends Message {
switchboardAction: Actions.GET;
method: string;
messageId: string;
args: T;
}

function isGet(message: Message): message is GetMessage {
return message.switchboardAction === Actions.GET;
}

interface ReplyMessage<T = any> extends Message {
switchboardAction: Actions.REPLY;
messageId: string;
result: T;
}

function isReply(message: Message): message is ReplyMessage {
return message.switchboardAction === Actions.REPLY;
}

interface EmitMessage<T = any> extends Message {
switchboardAction: Actions.EMIT;
method: string;
args: T;
}

function isEmit(message: Message): message is EmitMessage {
return message.switchboardAction === Actions.EMIT;
}

interface ErrorMessage extends Message {
switchboardAction: Actions.ERROR;
messageId: string;
error: string;
}

function isError(message: Message): message is ErrorMessage {
return message.switchboardAction === Actions.ERROR;
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,6 @@ import { FrameComponentProps } from 'src/explore/components/controls/DateFilterC
import DateFunctionTooltip from './DateFunctionTooltip';

export function AdvancedFrame(props: FrameComponentProps) {
const advancedRange = getAdvancedRange(props.value || '');
const [since, until] = advancedRange.split(SEPARATOR);
if (advancedRange !== props.value) {
props.onChange(getAdvancedRange(props.value || ''));
}

function getAdvancedRange(value: string): string {
if (value.includes(SEPARATOR)) {
return value;
Expand All @@ -44,6 +38,12 @@ export function AdvancedFrame(props: FrameComponentProps) {
return SEPARATOR;
}

const advancedRange = getAdvancedRange(props.value || '');
const [since, until] = advancedRange.split(SEPARATOR);
if (advancedRange !== props.value) {
props.onChange(getAdvancedRange(props.value || ''));
}

function onChange(control: 'since' | 'until', value: string) {
if (control === 'since') {
props.onChange(`${value}${SEPARATOR}${until}`);
Expand Down
148 changes: 74 additions & 74 deletions superset-frontend/src/middleware/asyncEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,46 +67,6 @@ let listenersByJobId: Record<string, ListenerFn>;
let retriesByJobId: Record<string, number>;
let lastReceivedEventId: string | null | undefined;

export const init = (appConfig?: AppConfig) => {
if (!isFeatureEnabled(FeatureFlag.GLOBAL_ASYNC_QUERIES)) return;
if (pollingTimeoutId) clearTimeout(pollingTimeoutId);

listenersByJobId = {};
retriesByJobId = {};
lastReceivedEventId = null;

if (appConfig) {
config = appConfig;
} else {
// load bootstrap data from DOM
const appContainer = document.getElementById('app');
if (appContainer) {
const bootstrapData = JSON.parse(
appContainer?.getAttribute('data-bootstrap') || '{}',
);
config = bootstrapData?.common?.conf;
} else {
config = {};
logging.warn('asyncEvent: app config data not found');
}
}
transport = config.GLOBAL_ASYNC_QUERIES_TRANSPORT || TRANSPORT_POLLING;
pollingDelayMs = config.GLOBAL_ASYNC_QUERIES_POLLING_DELAY || 500;

try {
lastReceivedEventId = localStorage.getItem(LOCALSTORAGE_KEY);
} catch (err) {
logging.warn('Failed to fetch last event Id from localStorage');
}

if (transport === TRANSPORT_POLLING) {
loadEventsFromApi();
}
if (transport === TRANSPORT_WS) {
wsConnect();
}
};

const addListener = (id: string, fn: any) => {
listenersByJobId[id] = fn;
};
Expand All @@ -116,6 +76,24 @@ const removeListener = (id: string) => {
delete listenersByJobId[id];
};

const fetchCachedData = async (
asyncEvent: AsyncEvent,
): Promise<CachedDataResponse> => {
let status = 'success';
let data;
try {
const { json } = await SupersetClient.get({
endpoint: String(asyncEvent.result_url),
});
data = 'result' in json ? json.result : json;
} catch (response) {
status = 'error';
data = await getClientErrorObject(response);
}

return { status, data };
};

export const waitForAsyncData = async (asyncResponse: AsyncEvent) =>
new Promise((resolve, reject) => {
const jobId = asyncResponse.job_id;
Expand Down Expand Up @@ -153,24 +131,6 @@ const fetchEvents = makeApi<
endpoint: POLLING_URL,
});

const fetchCachedData = async (
asyncEvent: AsyncEvent,
): Promise<CachedDataResponse> => {
let status = 'success';
let data;
try {
const { json } = await SupersetClient.get({
endpoint: String(asyncEvent.result_url),
});
data = 'result' in json ? json.result : json;
} catch (response) {
status = 'error';
data = await getClientErrorObject(response);
}

return { status, data };
};

const setLastId = (asyncEvent: AsyncEvent) => {
lastReceivedEventId = asyncEvent.id;
try {
Expand All @@ -180,22 +140,6 @@ const setLastId = (asyncEvent: AsyncEvent) => {
}
};

const loadEventsFromApi = async () => {
const eventArgs = lastReceivedEventId ? { last_id: lastReceivedEventId } : {};
if (Object.keys(listenersByJobId).length) {
try {
const { result: events } = await fetchEvents(eventArgs);
if (events && events.length) await processEvents(events);
} catch (err) {
logging.warn(err);
}
}

if (transport === TRANSPORT_POLLING) {
pollingTimeoutId = window.setTimeout(loadEventsFromApi, pollingDelayMs);
}
};

export const processEvents = async (events: AsyncEvent[]) => {
events.forEach((asyncEvent: AsyncEvent) => {
const jobId = asyncEvent.job_id;
Expand All @@ -222,6 +166,22 @@ export const processEvents = async (events: AsyncEvent[]) => {
});
};

const loadEventsFromApi = async () => {
const eventArgs = lastReceivedEventId ? { last_id: lastReceivedEventId } : {};
if (Object.keys(listenersByJobId).length) {
try {
const { result: events } = await fetchEvents(eventArgs);
if (events && events.length) await processEvents(events);
} catch (err) {
logging.warn(err);
}
}

if (transport === TRANSPORT_POLLING) {
pollingTimeoutId = window.setTimeout(loadEventsFromApi, pollingDelayMs);
}
};

const wsConnectMaxRetries = 6;
const wsConnectErrorDelay = 2500;
let wsConnectRetries = 0;
Expand Down Expand Up @@ -267,4 +227,44 @@ const wsConnect = (): void => {
});
};

export const init = (appConfig?: AppConfig) => {
if (!isFeatureEnabled(FeatureFlag.GLOBAL_ASYNC_QUERIES)) return;
if (pollingTimeoutId) clearTimeout(pollingTimeoutId);

listenersByJobId = {};
retriesByJobId = {};
lastReceivedEventId = null;

if (appConfig) {
config = appConfig;
} else {
// load bootstrap data from DOM
const appContainer = document.getElementById('app');
if (appContainer) {
const bootstrapData = JSON.parse(
appContainer?.getAttribute('data-bootstrap') || '{}',
);
config = bootstrapData?.common?.conf;
} else {
config = {};
logging.warn('asyncEvent: app config data not found');
}
}
transport = config.GLOBAL_ASYNC_QUERIES_TRANSPORT || TRANSPORT_POLLING;
pollingDelayMs = config.GLOBAL_ASYNC_QUERIES_POLLING_DELAY || 500;

try {
lastReceivedEventId = localStorage.getItem(LOCALSTORAGE_KEY);
} catch (err) {
logging.warn('Failed to fetch last event Id from localStorage');
}

if (transport === TRANSPORT_POLLING) {
loadEventsFromApi();
}
if (transport === TRANSPORT_WS) {
wsConnect();
}
};

init();
28 changes: 14 additions & 14 deletions superset-frontend/src/utils/localStorageHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,20 +66,6 @@ export type LocalStorageValues = {
explore__data_table_original_formatted_time_columns: Record<string, string[]>;
};

export function getItem<K extends LocalStorageKeys>(
key: K,
defaultValue: LocalStorageValues[K],
): LocalStorageValues[K] {
return dangerouslyGetItemDoNotUse(key, defaultValue);
}

export function setItem<K extends LocalStorageKeys>(
key: K,
value: LocalStorageValues[K],
): void {
dangerouslySetItemDoNotUse(key, value);
}

/*
* This function should not be used directly, as it doesn't provide any type safety or any
* guarantees that the globally namespaced localstorage key is correct.
Expand Down Expand Up @@ -116,3 +102,17 @@ export function dangerouslySetItemDoNotUse(key: string, value: any): void {
// Catch in case localStorage is unavailable
}
}

export function getItem<K extends LocalStorageKeys>(
key: K,
defaultValue: LocalStorageValues[K],
): LocalStorageValues[K] {
return dangerouslyGetItemDoNotUse(key, defaultValue);
}

export function setItem<K extends LocalStorageKeys>(
key: K,
value: LocalStorageValues[K],
): void {
dangerouslySetItemDoNotUse(key, value);
}
Loading