craig-rueda commented on a change in pull request #11499:
URL: 
https://github.com/apache/incubator-superset/pull/11499#discussion_r540404057



##########
File path: superset-frontend/src/middleware/asyncEvent.ts
##########
@@ -0,0 +1,194 @@
+/**
+ * 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 { Middleware, MiddlewareAPI, Dispatch } from 'redux';
+import { makeApi, SupersetClient } from '@superset-ui/core';
+import { SupersetError } from 'src/components/ErrorMessage/types';
+import { getFeatureFlag, isFeatureEnabled, FeatureFlag } from 
'../featureFlags';
+import {
+  getClientErrorObject,
+  parseErrorJson,
+} from '../utils/getClientErrorObject';
+
+export type AsyncEvent = {
+  id: string;
+  channel_id: string;
+  job_id: string;
+  user_id: string;
+  status: string;
+  errors: SupersetError[];
+  result_url: string;
+};
+
+type AsyncEventOptions = {
+  getPendingComponents: (state: any) => any[];
+  successAction: (componentId: number, componentData: any) => { type: string };
+  errorAction: (componentId: number, response: any) => { type: string };
+  processEventsCallback?: (events: AsyncEvent[]) => void; // this is currently 
used only for tests
+};
+
+type CachedDataResponse = {
+  componentId: number;
+  status: string;
+  data: any;
+};
+
+const initAsyncEvents = (options: AsyncEventOptions) => {
+  // TODO: implement websocket support
+  const TRANSPORT_POLLING = 'polling';
+  const config = getFeatureFlag(FeatureFlag.GLOBAL_ASYNC_QUERIES_OPTIONS) || 
{};
+  const transport = config.transport || TRANSPORT_POLLING;
+  const polling_delay = config.polling_delay || 500;
+  const {
+    getPendingComponents,
+    successAction,
+    errorAction,
+    processEventsCallback,
+  } = options;
+
+  const middleware: Middleware = <S>(store: MiddlewareAPI<S>) => (
+    next: Dispatch<S>,
+  ) => {
+    const JOB_STATUS = {
+      PENDING: 'pending',
+      RUNNING: 'running',
+      ERROR: 'error',
+      DONE: 'done',
+    };
+    const LOCALSTORAGE_KEY = 'last_async_event_id';
+    const POLLING_URL = '/api/v1/async_event/';
+    let lastReceivedEventId: string | null;
+
+    try {
+      lastReceivedEventId = localStorage.getItem(LOCALSTORAGE_KEY);
+    } catch (err) {
+      console.warn('failed to fetch last event Id from localStorage');
+    }
+
+    const fetchEvents = makeApi<
+      { last_id?: string | null },
+      { result: AsyncEvent[] }
+    >({
+      method: 'GET',
+      endpoint: POLLING_URL,
+    });
+
+    const fetchCachedData = async (
+      asyncEvent: AsyncEvent,
+      componentId: number,
+    ): Promise<CachedDataResponse> => {
+      let status = 'success';
+      let data;
+      try {
+        const { json } = await SupersetClient.get({
+          endpoint: asyncEvent.result_url,
+        });
+        data = 'result' in json ? json.result[0] : json;
+      } catch (response) {
+        status = 'error';
+        data = await getClientErrorObject(response);
+      }
+
+      return { componentId, status, data };
+    };
+
+    const setLastId = (asyncEvent: AsyncEvent) => {
+      lastReceivedEventId = asyncEvent.id;
+      try {
+        localStorage.setItem(LOCALSTORAGE_KEY, lastReceivedEventId as string);
+      } catch (err) {
+        console.warn('Error saving event ID to localStorage', err);
+      }
+    };
+
+    const processEvents = async () => {
+      const state = store.getState();
+      const queuedComponents = getPendingComponents(state);
+      const eventArgs = lastReceivedEventId
+        ? { last_id: lastReceivedEventId }
+        : {};
+      const events: AsyncEvent[] = [];
+      if (queuedComponents && queuedComponents.length) {
+        try {
+          const { result: events } = await fetchEvents(eventArgs);
+          if (events && events.length) {
+            const componentsByJobId = queuedComponents.reduce((acc, item) => {
+              acc[item.asyncJobId] = item;
+              return acc;
+            }, {});
+            const fetchDataEvents: Promise<CachedDataResponse>[] = [];
+            events.forEach((asyncEvent: AsyncEvent) => {
+              const component = componentsByJobId[asyncEvent.job_id];
+              if (!component) {
+                console.warn(
+                  'component not found for job_id',
+                  asyncEvent.job_id,
+                );
+                return setLastId(asyncEvent);
+              }
+              const componentId = component.id;
+              switch (asyncEvent.status) {
+                case JOB_STATUS.DONE:
+                  fetchDataEvents.push(
+                    fetchCachedData(asyncEvent, componentId),
+                  );
+                  break;
+                case JOB_STATUS.ERROR:
+                  store.dispatch(
+                    errorAction(componentId, parseErrorJson(asyncEvent)),
+                  );
+                  break;
+                default:
+                  console.warn('received event with status', 
asyncEvent.status);
+              }
+
+              return setLastId(asyncEvent);
+            });
+
+            const fetchResults = await Promise.all(fetchDataEvents);

Review comment:
       Wondering if it's most performant to do an `all` here... This will cause 
all results to be loaded at once into memory as data is fetched (not that it 
doesn't already after landing in the DOM), but from a GC POV, it might be 
better to just iterate over your collected promises and resolve each, as you go




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
[email protected]



---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to