villebro commented on code in PR #36368:
URL: https://github.com/apache/superset/pull/36368#discussion_r2738499946


##########
superset/tasks/api.py:
##########
@@ -0,0 +1,492 @@
+# 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.
+"""Task REST API"""
+
+import logging
+from typing import TYPE_CHECKING
+
+from flask import Response
+from flask_appbuilder.api import expose, protect, safe
+from flask_appbuilder.models.sqla.interface import SQLAInterface
+
+from superset.commands.tasks.cancel import CancelTaskCommand
+from superset.commands.tasks.exceptions import (
+    TaskAbortFailedError,
+    TaskForbiddenError,
+    TaskNotAbortableError,
+    TaskNotFoundError,
+    TaskPermissionDeniedError,
+)
+from superset.constants import MODEL_API_RW_METHOD_PERMISSION_MAP, RouteMethod
+from superset.extensions import event_logger
+from superset.models.tasks import Task
+from superset.tasks.filters import TaskFilter
+from superset.tasks.schemas import (
+    openapi_spec_methods_override,
+    TaskCancelRequestSchema,
+    TaskCancelResponseSchema,
+    TaskResponseSchema,
+    TaskStatusResponseSchema,
+)
+from superset.views.base_api import (
+    BaseSupersetModelRestApi,
+    RelatedFieldFilter,
+    statsd_metrics,
+)
+from superset.views.filters import BaseFilterRelatedUsers, FilterRelatedOwners
+
+if TYPE_CHECKING:
+    pass
+
+logger = logging.getLogger(__name__)
+
+
+class TaskRestApi(BaseSupersetModelRestApi):
+    """REST API for task management"""
+
+    datamodel = SQLAInterface(Task)
+    resource_name = "task"
+    allow_browser_login = True
+
+    class_permission_name = "Task"
+
+    # Map cancel and status to write/read permissions
+    method_permission_name = {
+        **MODEL_API_RW_METHOD_PERMISSION_MAP,
+        "cancel": "write",
+        "status": "read",
+    }
+
+    include_route_methods = RouteMethod.REST_MODEL_VIEW_CRUD_SET | {
+        "cancel",
+        "status",
+        "related_subscribers",
+        "related",
+    }
+
+    list_columns = [
+        "id",
+        "uuid",
+        "task_type",
+        "task_key",
+        "task_name",
+        "scope",
+        "status",
+        "created_on",
+        "created_on_delta_humanized",
+        "changed_on",
+        "changed_by.first_name",
+        "changed_by.last_name",
+        "started_at",
+        "ended_at",
+        "created_by.id",
+        "created_by.first_name",
+        "created_by.last_name",
+        "user_id",
+        "payload",
+        "properties",
+        "duration_seconds",
+        "subscriber_count",
+        "subscribers",
+    ]
+
+    list_select_columns = list_columns + ["created_by_fk", "changed_by_fk"]
+
+    show_columns = list_columns
+
+    order_columns = [
+        "task_type",
+        "scope",
+        "status",
+        "created_on",
+        "changed_on",
+        "started_at",
+        "ended_at",
+    ]
+
+    search_columns = [
+        "task_type",
+        "task_key",
+        "task_name",
+        "scope",
+        "status",
+        "created_by",
+        "created_on",
+    ]
+
+    base_order = ("created_on", "desc")
+    base_filters = [["id", TaskFilter, lambda: []]]
+
+    # Related field configuration for filter dropdowns
+    allowed_rel_fields = {"created_by"}
+    related_field_filters = {
+        "created_by": RelatedFieldFilter("first_name", FilterRelatedOwners),
+    }
+    base_related_field_filters = {
+        "created_by": [["id", BaseFilterRelatedUsers, lambda: []]],
+    }
+
+    show_model_schema = TaskResponseSchema()
+    list_model_schema = TaskResponseSchema()
+    cancel_request_schema = TaskCancelRequestSchema()
+
+    openapi_spec_tag = "Tasks"
+    openapi_spec_component_schemas = (
+        TaskResponseSchema,
+        TaskCancelRequestSchema,
+        TaskCancelResponseSchema,
+        TaskStatusResponseSchema,
+    )
+    openapi_spec_methods = openapi_spec_methods_override
+
+    @expose("/<uuid_or_id>", methods=("GET",))
+    @protect()
+    @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, uuid_or_id: str) -> Response:
+        """Get a task.
+        ---
+        get:
+          summary: Get a task
+          parameters:
+          - in: path
+            schema:
+              type: string
+            name: uuid_or_id
+            description: The UUID or ID of the task
+          responses:
+            200:
+              description: Task detail
+              content:
+                application/json:
+                  schema:
+                    type: object
+                    properties:
+                      result:
+                        $ref: '#/components/schemas/TaskResponseSchema'
+            401:
+              $ref: '#/components/responses/401'
+            403:
+              $ref: '#/components/responses/403'
+            404:
+              $ref: '#/components/responses/404'
+        """
+        try:
+            # Try to find by UUID first, then by ID
+            if len(uuid_or_id) == 36 or "-" in uuid_or_id:
+                # Lazy import to avoid circular dependency
+                from superset.daos.tasks import TaskDAO
+
+                task = TaskDAO.find_one_or_none(uuid=uuid_or_id)
+            else:
+                # Lazy import to avoid circular dependency
+                from superset.daos.tasks import TaskDAO
+
+                task = TaskDAO.find_by_id(int(uuid_or_id))
+
+            if not task:
+                return self.response_404()
+
+            result = self.show_model_schema.dump(task)
+            return self.response(200, result=result)
+        except (ValueError, TypeError):
+            return self.response_404()
+
+    @expose("/<uuid_or_id>/status", methods=("GET",))
+    @protect()
+    @safe
+    @statsd_metrics
+    @event_logger.log_this_with_context(
+        action=lambda self, *args, **kwargs: 
f"{self.__class__.__name__}.status",
+        log_to_statsd=False,
+    )
+    def status(self, uuid_or_id: str) -> Response:
+        """Get only the status of a task (lightweight for polling).
+        ---
+        get:
+          summary: Get task status
+          parameters:
+          - in: path
+            schema:
+              type: string
+            name: uuid_or_id
+            description: The UUID or ID of the task
+          responses:
+            200:
+              description: Task status
+              content:
+                application/json:
+                  schema:
+                    type: object
+                    properties:
+                      status:
+                        type: string
+                        description: Current status of the task
+            401:
+              $ref: '#/components/responses/401'
+            403:
+              $ref: '#/components/responses/403'
+            404:
+              $ref: '#/components/responses/404'
+        """
+        try:
+            # Try to find by UUID first, then by ID
+            if len(uuid_or_id) == 36 or "-" in uuid_or_id:
+                # Lazy import to avoid circular dependency
+                from superset.daos.tasks import TaskDAO

Review Comment:
   There was definitely some AI slop leftover here, thanks for flagging. 
However, inline importing DAOs is a well established pattern throughout the 
codebase. I cleaned these up to be in line with conventions elsewhere and 
propose deferring to a bigger refactor to address this more universally.



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

Reply via email to