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



##########
File path: superset/utils/async_query_manager.py
##########
@@ -0,0 +1,200 @@
+# 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 json
+import logging
+import uuid
+from typing import Any, Dict, List, Optional, Tuple
+
+import jwt
+import redis
+from flask import Flask, Request, Response, session
+
+logger = logging.getLogger(__name__)
+
+
+class AsyncQueryTokenException(Exception):
+    pass
+
+
+class AsyncQueryJobException(Exception):
+    pass
+
+
+def build_job_metadata(channel_id: str, job_id: str, **kwargs: Any) -> 
Dict[str, Any]:
+    return {
+        "channel_id": channel_id,
+        "job_id": job_id,
+        "user_id": session.get("user_id"),
+        "status": kwargs.get("status"),
+        "errors": kwargs.get("errors", []),
+        "result_url": kwargs.get("result_url"),
+    }
+
+
+def parse_event(event_data: Tuple[str, Dict[str, Any]]) -> Dict[str, Any]:
+    event_id = event_data[0]
+    event_payload = event_data[1]["data"]
+    return {"id": event_id, **json.loads(event_payload)}
+
+
+def increment_id(redis_id: str) -> str:
+    # redis stream IDs are in this format: '1607477697866-0'
+    try:
+        prefix, last = redis_id[:-1], int(redis_id[-1])
+        return prefix + str(last + 1)
+    except Exception:  # pylint: disable=broad-except
+        return redis_id
+
+
+class AsyncQueryManager:
+    MAX_EVENT_COUNT = 100
+    STATUS_PENDING = "pending"
+    STATUS_RUNNING = "running"
+    STATUS_ERROR = "error"
+    STATUS_DONE = "done"
+
+    def __init__(self) -> None:
+        super().__init__()
+        self._redis: redis.Redis
+        self._stream_prefix: str = ""
+        self._stream_limit: Optional[int]
+        self._stream_limit_firehose: Optional[int]
+        self._jwt_cookie_name: str
+        self._jwt_cookie_secure: bool = False
+        self._jwt_secret: str
+
+    def init_app(self, app: Flask) -> None:
+        config = app.config
+        if (
+            config["CACHE_CONFIG"]["CACHE_TYPE"] == "null"
+            or config["DATA_CACHE_CONFIG"]["CACHE_TYPE"] == "null"
+        ):
+            raise Exception(
+                """
+                Cache backends (CACHE_CONFIG, DATA_CACHE_CONFIG) must be 
configured
+                and non-null in order to enable async queries
+                """
+            )
+
+        if len(config["GLOBAL_ASYNC_QUERIES_JWT_SECRET"]) < 32:
+            raise AsyncQueryTokenException(
+                "Please provide a JWT secret at least 32 bytes long"
+            )
+
+        self._redis = redis.Redis(  # type: ignore
+            **config["GLOBAL_ASYNC_QUERIES_REDIS_CONFIG"], 
decode_responses=True
+        )
+        self._stream_prefix = 
config["GLOBAL_ASYNC_QUERIES_REDIS_STREAM_PREFIX"]
+        self._stream_limit = config["GLOBAL_ASYNC_QUERIES_REDIS_STREAM_LIMIT"]
+        self._stream_limit_firehose = config[
+            "GLOBAL_ASYNC_QUERIES_REDIS_STREAM_LIMIT_FIREHOSE"
+        ]
+        self._jwt_cookie_name = config["GLOBAL_ASYNC_QUERIES_JWT_COOKIE_NAME"]
+        self._jwt_cookie_secure = 
config["GLOBAL_ASYNC_QUERIES_JWT_COOKIE_SECURE"]
+        self._jwt_secret = config["GLOBAL_ASYNC_QUERIES_JWT_SECRET"]
+
+        @app.after_request
+        def validate_session(  # pylint: disable=unused-variable
+            response: Response,
+        ) -> Response:
+            reset_token = False
+            user_id = session["user_id"] if "user_id" in session else None
+
+            if "async_channel_id" not in session or "async_user_id" not in 
session:
+                reset_token = True
+            elif user_id != session["async_user_id"]:
+                reset_token = True
+
+            if reset_token:
+                async_channel_id = str(uuid.uuid4())
+                session["async_channel_id"] = async_channel_id
+                session["async_user_id"] = user_id
+
+                token = self.generate_jwt(
+                    {"channel": async_channel_id, "user_id": user_id}
+                )
+
+                response.set_cookie(
+                    self._jwt_cookie_name,
+                    value=token,
+                    httponly=True,
+                    secure=self._jwt_cookie_secure,
+                    # max_age=max_age or config.cookie_max_age,
+                    # domain=config.cookie_domain,
+                    # path=config.access_cookie_path,
+                    # samesite=config.cookie_samesite
+                )
+
+            return response
+
+    def generate_jwt(self, data: Dict[str, Any]) -> str:
+        encoded_jwt = jwt.encode(data, self._jwt_secret, algorithm="HS256")

Review comment:
       > [4.1.  Registered Claim 
Names](https://tools.ietf.org/html/rfc7519#section-4.1)
   > None of the claims defined below are intended to be mandatory to use or 
implement in all
      cases, but rather they provide a starting point for a set of useful,
      interoperable claims.  Applications using JWTs should define which
      specific claims they use and when they are required or optional.




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