ellisms commented on code in PR #64274:
URL: https://github.com/apache/airflow/pull/64274#discussion_r3283989151


##########
providers/amazon/src/airflow/providers/amazon/aws/operators/neptune_analytics.py:
##########
@@ -0,0 +1,1006 @@
+#
+# 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
+
+from collections.abc import Sequence
+from typing import TYPE_CHECKING, Any
+
+from botocore.exceptions import ClientError
+
+from airflow.providers.amazon.aws.hooks.neptune_analytics import 
NeptuneAnalyticsHook
+from airflow.providers.amazon.aws.links.ec2 import VpcEndpointLink
+from airflow.providers.amazon.aws.links.neptune_analytics import 
NeptuneGraphLink, NeptuneImportTaskLink
+from airflow.providers.amazon.aws.operators.base_aws import AwsBaseOperator
+from airflow.providers.amazon.aws.triggers.neptune_analytics import (
+    NeptuneGraphAvailableTrigger,
+    NeptuneGraphDeletedTrigger,
+    NeptuneGraphPrivateEndpointAvailableTrigger,
+    NeptuneGraphPrivateEndpointDeletedTrigger,
+    NeptuneImportTaskCancelledTrigger,
+    NeptuneImportTaskCompleteTrigger,
+)
+from airflow.providers.amazon.aws.utils.mixins import aws_template_fields
+from airflow.providers.common.compat.sdk import conf
+
+if TYPE_CHECKING:
+    from airflow.sdk import Context
+
+from airflow.providers.amazon.aws.exceptions import (
+    NeptuneGraphCreationFailedError,
+    NeptuneGraphDeletionFailedError,
+    NeptuneImportTaskCancellationFailedError,
+    NeptunePrivateEndpointCreationFailedError,
+    NeptunePrivateEndpointDeletionFailedError,
+)
+
+
+class NeptuneCreateGraphOperator(AwsBaseOperator[NeptuneAnalyticsHook]):
+    """
+    Creates an empty Amazon Neptune Graph database.
+
+    Neptune Analytics is a memory-optimized graph database engine for 
analytics. With Neptune Analytics, you can get insights and find trends by 
processing large amounts of graph data in seconds.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the 
guide:
+        :ref:`howto/operator:NeptuneCreateGraphOperator`
+
+    :param graph_name: Name of Neptune graph to create
+    :param vector_search_config: Specifies the number of dimensions for vector 
embeddings that will be loaded into the graph.
+    :param provisioned_memory: The provisioned memory-optimized Neptune 
Capacity Units (m-NCUs) to use for the graph.
+    :param public_connectivity: Specifies whether or not the graph can be 
reachable over the internet.
+    :param replica_count: The number of replicas in other AZs.
+    :param deletion_protection:  Indicates whether or not to enable deletion 
protection on the graph.
+        The graph can't be deleted when deletion protection is enabled.
+    :param kms_key_id:  Specifies a KMS key to use to encrypt data in the new 
graph.
+    :param tags: Specifies metadata tags to add to the graph.
+    :param wait_for_completion: Whether to wait for the graph to start. 
(default: True)
+    :param deferrable: If True, the operator will wait asynchronously for the 
graph to start.
+        This implies waiting for completion. This mode requires aiobotocore 
module to be installed.
+        (default: False)
+    :param waiter_delay: Time in seconds to wait between status checks.
+    :param waiter_max_attempts: Maximum number of attempts to check for job 
completion.
+    :param aws_conn_id: The Airflow connection used for AWS credentials.
+        If this is ``None`` or empty then the default boto3 behaviour is used. 
If
+        running Airflow in a distributed manner and aws_conn_id is None or
+        empty, then default boto3 configuration would be used (and must be
+        maintained on each worker node).
+    :param region_name: AWS region_name. If not specified then the default 
boto3 behaviour is used.
+    :param botocore_config: Configuration dictionary (key-values) for botocore 
client. See:
+        
https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
+    :return: dictionary with Neptune graph id
+    """
+
+    aws_hook_class = NeptuneAnalyticsHook
+    template_fields: Sequence[str] = aws_template_fields(
+        "graph_name", "vector_search_config", "provisioned_memory"
+    )
+
+    template_fields_renderers = {
+        "vector_search_config": "json",
+    }
+
+    operator_extra_links = (NeptuneGraphLink(),)
+
+    def __init__(
+        self,
+        graph_name: str,
+        vector_search_config: dict,
+        provisioned_memory: int,
+        public_connectivity: bool | None = None,
+        replica_count: int | None = None,
+        deletion_protection: bool = False,
+        kms_key_id: str | None = None,
+        tags: dict | None = None,
+        wait_for_completion: bool = True,
+        waiter_delay: int = 30,
+        waiter_max_attempts: int = 60,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", 
fallback=False),
+        **kwargs,
+    ):
+        super().__init__(**kwargs)
+        self.graph_name = graph_name
+        self.vector_search_config = vector_search_config
+        self.replica_count = replica_count
+        self.provisioned_memory = provisioned_memory
+        self.public_connectivity = public_connectivity
+        self.deletion_protect = deletion_protection
+        self.kms_key = kms_key_id
+        self.tags = tags
+        self.wait_for_completion = wait_for_completion
+        self.deferrable = deferrable
+        self.waiter_delay = waiter_delay
+        self.waiter_max_attempts = waiter_max_attempts
+
+    def execute(self, context: Context) -> dict:
+        self.log.info("Creating graph %s", self.graph_name)
+
+        create_params = {
+            "graphName": self.graph_name,
+            "vectorSearchConfiguration": self.vector_search_config,
+            "provisionedMemory": self.provisioned_memory,
+            **{
+                k: v
+                for k, v in {
+                    "replicaCount": self.replica_count,
+                    "publicConnectivity": self.public_connectivity,
+                    "deletionProtection": self.deletion_protect,
+                    "kmsKeyIdentifier": self.kms_key,
+                    "tags": self.tags,
+                }.items()
+                if v is not None
+            },
+        }
+
+        response = self.hook.conn.create_graph(**create_params)
+
+        self.log.info("Graph %s in status %s", self.graph_name, 
response.get("status", "Unknown"))
+        self.graph_id = response.get("id", None)
+
+        graph_url = NeptuneGraphLink.format_str.format(
+            graph_id=self.graph_id,
+            
aws_domain=NeptuneGraphLink.get_aws_domain(self.hook.conn_partition),
+            region_name=self.hook.conn_region_name,
+        )
+
+        NeptuneGraphLink.persist(
+            context=context,
+            operator=self,
+            region_name=self.hook.conn_region_name,
+            aws_partition=self.hook.conn_partition,
+            graph_id=self.graph_id,
+        )
+        self.log.info("You can view this Neptune Graph at : %s", graph_url)
+
+        if self.deferrable:
+            self.log.info("Deferring until graph %s is available", 
self.graph_id)
+            self.defer(
+                trigger=NeptuneGraphAvailableTrigger(
+                    aws_conn_id=self.aws_conn_id,
+                    graph_id=self.graph_id,
+                    waiter_delay=self.waiter_delay,
+                    waiter_max_attempts=self.waiter_max_attempts,
+                ),
+                method_name="execute_complete",
+            )
+
+        if self.wait_for_completion:
+            self.log.info("Waiting until graph %s is available", self.graph_id)
+            self.hook.get_waiter("graph_available").wait(
+                graphIdentifier=self.graph_id,
+                WaiterConfig={"Delay": self.waiter_delay, "MaxAttempts": 
self.waiter_max_attempts},
+            )
+
+        return {"graph_id": self.graph_id}
+
+    def execute_complete(self, context: Context, event: dict[str, Any] | None 
= None) -> dict[str, Any]:
+        if event is None:
+            raise NeptuneGraphCreationFailedError(
+                "No event received while waiting for Neptune graph creation to 
complete."
+            )
+
+        if event.get("status") != "success":
+            raise NeptuneGraphCreationFailedError(
+                event.get(
+                    "message",
+                    f"Neptune graph {self.graph_id} creation did not complete 
successfully: {event}",
+                )
+            )
+
+        self.log.info("Neptune graph %s complete", self.graph_id)

Review Comment:
   Ah, didn't realize there is a helper function. Will implement.



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