perry2of5 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1900278576


##########
airflow/cli/api/operations.py:
##########
@@ -0,0 +1,675 @@
+# 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.
+
+from __future__ import annotations
+
+import datetime
+import sys
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import rich
+import structlog
+
+from airflow.cli.api.datamodels._generated import (
+    AssetAliasCollectionResponse,
+    AssetAliasResponse,
+    AssetCollectionResponse,
+    AssetResponse,
+    BackfillPostBody,
+    BackfillResponse,
+    Config,
+    ConnectionBody,
+    ConnectionBulkBody,
+    ConnectionCollectionResponse,
+    ConnectionResponse,
+    ConnectionTestResponse,
+    DAGDetailsResponse,
+    DAGResponse,
+    DAGRunCollectionResponse,
+    DAGRunResponse,
+    JobCollectionResponse,
+    PoolCollectionResponse,
+    PoolPatchBody,
+    PoolPostBody,
+    PoolPostBulkBody,
+    PoolResponse,
+    ProviderCollectionResponse,
+    TriggerDAGRunPostBody,
+    VariableBody,
+    VariableCollectionResponse,
+    VariableResponse,
+    VersionInfo,
+)
+
+if TYPE_CHECKING:
+    from airflow.cli.api.client import Client
+    from airflow.utils.state import DagRunState
+
+log = structlog.get_logger(logger_name=__name__)
+
+
+# Generic Server Response Error
+class ServerResponseError(httpx.HTTPStatusError):
+    """Server response error (Generic)."""
+
+    def __init__(self, message: str, *, request: httpx.Request, response: 
httpx.Response):
+        super().__init__(message, request=request, response=response)
+
+    # def_
+
+    @classmethod
+    def from_response(cls, response: httpx.Response) -> ServerResponseError | 
None:
+        if response.status_code < 400:
+            return None
+
+        if response.headers.get("content-type") != "application/json":
+            return None
+
+        if 400 <= response.status_code < 500:
+            response.read()
+            return cls(
+                message=f"Client error message: {response.json()}",
+                request=response.request,
+                response=response,
+            )
+
+        msg = response.json()
+
+        self = cls(message=msg, request=response.request, response=response)
+        return self
+
+
+# Decorator to apply methods to all operations, this is initiated at 
__init_subclass__ on BaseOperations
+SERVER_CONNECTION_REFUSED_ERROR: str = "API Server is not running, please 
contact your administrator."
+
+
+def _check_flag_and_exit_if_server_response_error(func):
+    """Return decorator to check for ServerResponseError and exit if the 
server is not running."""
+
+    def _exit_if_server_response_error(response: Any | ServerResponseError):
+        if isinstance(response, ServerResponseError):
+            rich.print(f"[bold red]Error:[/bold red] 
{response.response.json()}")
+            sys.exit(1)
+        return response
+
+    def wrapped(self, *args, **kwargs):
+        try:
+            if self.exit_in_error:
+                return _exit_if_server_response_error(response=func(self, 
*args, **kwargs))
+            else:
+                return func(self, *args, **kwargs)
+        except httpx.ConnectError:
+            rich.print(f"[bold red]{SERVER_CONNECTION_REFUSED_ERROR}[/bold 
red]")
+            sys.exit(1)
+
+    return wrapped
+
+
+class BaseOperations:
+    """
+    Base class for operations.
+
+    This class is used to decorate all callable methods with a check for 
ServerResponseError.
+    Set exit_in_error false to not exit.
+    """
+
+    __slots__ = ("client", "response", "exit_in_error")
+
+    def __init__(self, client: Client, response=None, exit_in_error: bool = 
True):
+        self.client = client
+        self.response = response
+        self.exit_in_error = exit_in_error
+
+    def __init_subclass__(cls, **kwargs):
+        """Decorate all callable methods with a check for ServerResponseError 
and exit if the server is not running."""
+        super().__init_subclass__(**kwargs)
+        for attr, value in cls.__dict__.items():
+            if callable(value):
+                setattr(cls, attr, 
_check_flag_and_exit_if_server_response_error(value))
+
+
+# Operations
+# TODO: Get all with limit and offset to overcome default 100 limit for all 
list operations

Review Comment:
   Would paging the results be better than getting all? Perhaps the 
XxxxCollectionResponse could track the limit and offset of the current 
collection and have next_page() and prev_page() methods. This would require the 
XxxxCollectionResponse contain a link back to the operator I suppose. This 
seems a little cleaner than having the consumer manipulate the limit and offset 
locally to page the results. I'm wary of getting all in a single call since the 
result size could be large. Probably not an actual issue in this context.



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

Reply via email to