josh-fell commented on code in PR #26038:
URL: https://github.com/apache/airflow/pull/26038#discussion_r957359045


##########
airflow/providers/microsoft/azure/hooks/synapse.py:
##########
@@ -0,0 +1,198 @@
+# 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 time
+from typing import Any, Dict, Optional, Set, Union
+
+from azure.identity import ClientSecretCredential, DefaultAzureCredential
+from azure.synapse.spark import SparkClient
+from azure.synapse.spark.models import SparkBatchJobOptions
+
+from airflow.hooks.base import BaseHook
+
+Credentials = Union[ClientSecretCredential, DefaultAzureCredential]
+
+
+class AzureSynapseSparkBatchRunStatus:
+    """Azure Synapse Spark Job operation statuses."""
+
+    NOT_STARTED = 'not_started'
+    STARTING = 'starting'
+    RUNNING = 'running'
+    IDLE = 'idle'
+    BUSY = 'busy'
+    SHUTTING_DOWN = 'shutting_down'
+    ERROR = 'error'
+    DEAD = 'dead'
+    KILLED = 'killed'
+    SUCCESS = 'success'
+
+    TERMINAL_STATUSES = {SUCCESS, DEAD, KILLED, ERROR}
+
+
+class AzureSynapseHook(BaseHook):
+    """
+    A hook to interact with Azure Synapse.
+
+    :param azure_synapse_conn_id: The :ref:`Azure Synapse connection 
id<howto/connection:synapse>`.
+    """
+
+    conn_type: str = 'azure_synapse'
+    conn_name_attr: str = 'azure_synapse_conn_id'
+    default_conn_name: str = 'azure_synapse_default'
+    hook_name: str = 'Azure Synapse'
+
+    @staticmethod
+    def get_connection_form_widgets() -> Dict[str, Any]:
+        """Returns connection widgets to add to connection form"""
+        from flask_appbuilder.fieldwidgets import BS3TextFieldWidget
+        from flask_babel import lazy_gettext
+        from wtforms import StringField
+
+        return {
+            "extra__azure_synapse__tenantId": StringField(
+                lazy_gettext('Tenant ID'), widget=BS3TextFieldWidget()
+            ),
+            "extra__azure_synapse__subscriptionId": StringField(
+                lazy_gettext('Subscription ID'), widget=BS3TextFieldWidget()
+            ),
+        }
+
+    @staticmethod
+    def get_ui_field_behaviour() -> Dict[str, Any]:
+        """Returns custom field behaviour"""
+        return {
+            "hidden_fields": ['schema', 'port', 'extra'],
+            "relabeling": {'login': 'Client ID', 'password': 'Secret', 'host': 
'Synapse Workspace URL'},
+        }
+
+    def __init__(self, azure_synapse_conn_id: str = default_conn_name, 
spark_pool: str = ''):
+        self._conn: Optional[SparkClient] = None
+        self.conn_id = azure_synapse_conn_id
+        self.spark_pool = spark_pool
+        super().__init__()
+
+    def get_conn(self) -> SparkClient:
+        if self._conn is not None:
+            return self._conn
+
+        conn = self.get_connection(self.conn_id)
+        tenant = conn.extra_dejson.get('extra__azure_synapse__tenantId')
+        spark_pool = self.spark_pool
+        livy_api_version = "2022-02-22-preview"
+
+        try:
+            subscription_id = 
conn.extra_dejson['extra__azure_synapse__subscriptionId']
+        except KeyError:
+            raise ValueError("A Subscription ID is required to connect to 
Azure Synapse.")
+
+        credential: Credentials
+        if conn.login is not None and conn.password is not None:
+            if not tenant:
+                raise ValueError("A Tenant ID is required when authenticating 
with Client ID and Secret.")
+
+            credential = ClientSecretCredential(
+                client_id=conn.login, client_secret=conn.password, 
tenant_id=tenant
+            )
+        else:
+            credential = DefaultAzureCredential()
+
+        self._conn = self._create_client(credential, conn.host, spark_pool, 
livy_api_version, subscription_id)
+
+        return self._conn
+
+    @staticmethod
+    def _create_client(credential: Credentials, host, spark_pool, 
livy_api_version, subscription_id: str):
+        return SparkClient(
+            credential=credential,
+            endpoint=host,
+            spark_pool_name=spark_pool,
+            livy_api_version=livy_api_version,
+            subscription_id=subscription_id,
+        )
+
+    def run_spark_job(
+        self,
+        payload: SparkBatchJobOptions,
+    ):
+        """
+        Run a job in an Apache Spark pool.
+
+        :param payload: Livy compatible payload which represents the spark job 
that a user wants to submit.
+        """
+        job = self.get_conn().spark_batch.create_spark_batch_job(payload)
+        self.job_id = job.id
+        return job
+
+    def get_job_run_status(
+        self,
+        job_id: int,
+    ):
+        """
+        Get the job run status.
+
+        :param job_id: The job identifier.
+        """
+        job_run_status = 
self.get_conn().spark_batch.get_spark_batch_job(batch_id=job_id).state
+        return job_run_status
+
+    def wait_for_job_run_status(
+        self,
+        job_id: int,
+        expected_statuses: Union[str, Set[str]],
+        check_interval: int = 60,
+        timeout: int = 60 * 60 * 24 * 7,
+    ) -> bool:
+        """
+        Waits for a job run to match an expected status.
+
+        :param job_id: The job run identifier.
+        :param expected_statuses: The desired status(es) to check against a 
job run's current status.
+        :param check_interval: Time in seconds to check on a job run's status.
+        :param timeout: Time in seconds to wait for a job to reach a terminal 
status or the expected
+            status.
+        """
+        job_run_status = self.get_job_run_status(job_id)
+        start_time = time.monotonic()
+
+        while (
+            job_run_status not in 
AzureSynapseSparkBatchRunStatus.TERMINAL_STATUSES
+            and job_run_status not in expected_statuses
+        ):
+            # Check if the job-run duration has exceeded the ``timeout`` 
configured.
+            if start_time + timeout < time.monotonic():
+                raise Exception(f"Job {job_id} has not reached a terminal 
status after {timeout} seconds.")

Review Comment:
   ```suggestion
                   raise AirflowTaskTimeout(f"Job {job_id} has not reached a 
terminal status after {timeout} seconds.")
   ```
   WDYT about using `AirflowTaskTimeout` exception instead?



##########
airflow/providers/microsoft/azure/hooks/synapse.py:
##########
@@ -0,0 +1,198 @@
+# 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 time
+from typing import Any, Dict, Optional, Set, Union
+
+from azure.identity import ClientSecretCredential, DefaultAzureCredential
+from azure.synapse.spark import SparkClient
+from azure.synapse.spark.models import SparkBatchJobOptions
+
+from airflow.hooks.base import BaseHook
+
+Credentials = Union[ClientSecretCredential, DefaultAzureCredential]
+
+
+class AzureSynapseSparkBatchRunStatus:
+    """Azure Synapse Spark Job operation statuses."""
+
+    NOT_STARTED = 'not_started'
+    STARTING = 'starting'
+    RUNNING = 'running'
+    IDLE = 'idle'
+    BUSY = 'busy'
+    SHUTTING_DOWN = 'shutting_down'
+    ERROR = 'error'
+    DEAD = 'dead'
+    KILLED = 'killed'
+    SUCCESS = 'success'
+
+    TERMINAL_STATUSES = {SUCCESS, DEAD, KILLED, ERROR}
+
+
+class AzureSynapseHook(BaseHook):
+    """
+    A hook to interact with Azure Synapse.
+
+    :param azure_synapse_conn_id: The :ref:`Azure Synapse connection 
id<howto/connection:synapse>`.
+    """
+
+    conn_type: str = 'azure_synapse'
+    conn_name_attr: str = 'azure_synapse_conn_id'
+    default_conn_name: str = 'azure_synapse_default'
+    hook_name: str = 'Azure Synapse'
+
+    @staticmethod
+    def get_connection_form_widgets() -> Dict[str, Any]:
+        """Returns connection widgets to add to connection form"""
+        from flask_appbuilder.fieldwidgets import BS3TextFieldWidget
+        from flask_babel import lazy_gettext
+        from wtforms import StringField
+
+        return {
+            "extra__azure_synapse__tenantId": StringField(
+                lazy_gettext('Tenant ID'), widget=BS3TextFieldWidget()
+            ),
+            "extra__azure_synapse__subscriptionId": StringField(
+                lazy_gettext('Subscription ID'), widget=BS3TextFieldWidget()
+            ),
+        }
+
+    @staticmethod
+    def get_ui_field_behaviour() -> Dict[str, Any]:
+        """Returns custom field behaviour"""
+        return {
+            "hidden_fields": ['schema', 'port', 'extra'],
+            "relabeling": {'login': 'Client ID', 'password': 'Secret', 'host': 
'Synapse Workspace URL'},
+        }
+
+    def __init__(self, azure_synapse_conn_id: str = default_conn_name, 
spark_pool: str = ''):

Review Comment:
   Can you add `spark_pool` to the docstring please?



##########
airflow/providers/microsoft/azure/hooks/synapse.py:
##########
@@ -0,0 +1,198 @@
+# 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 time
+from typing import Any, Dict, Optional, Set, Union
+
+from azure.identity import ClientSecretCredential, DefaultAzureCredential
+from azure.synapse.spark import SparkClient
+from azure.synapse.spark.models import SparkBatchJobOptions
+
+from airflow.hooks.base import BaseHook
+
+Credentials = Union[ClientSecretCredential, DefaultAzureCredential]
+
+
+class AzureSynapseSparkBatchRunStatus:
+    """Azure Synapse Spark Job operation statuses."""
+
+    NOT_STARTED = 'not_started'
+    STARTING = 'starting'
+    RUNNING = 'running'
+    IDLE = 'idle'
+    BUSY = 'busy'
+    SHUTTING_DOWN = 'shutting_down'
+    ERROR = 'error'
+    DEAD = 'dead'
+    KILLED = 'killed'
+    SUCCESS = 'success'
+
+    TERMINAL_STATUSES = {SUCCESS, DEAD, KILLED, ERROR}
+
+
+class AzureSynapseHook(BaseHook):
+    """
+    A hook to interact with Azure Synapse.
+
+    :param azure_synapse_conn_id: The :ref:`Azure Synapse connection 
id<howto/connection:synapse>`.
+    """
+
+    conn_type: str = 'azure_synapse'
+    conn_name_attr: str = 'azure_synapse_conn_id'
+    default_conn_name: str = 'azure_synapse_default'
+    hook_name: str = 'Azure Synapse'
+
+    @staticmethod
+    def get_connection_form_widgets() -> Dict[str, Any]:
+        """Returns connection widgets to add to connection form"""
+        from flask_appbuilder.fieldwidgets import BS3TextFieldWidget
+        from flask_babel import lazy_gettext
+        from wtforms import StringField
+
+        return {
+            "extra__azure_synapse__tenantId": StringField(
+                lazy_gettext('Tenant ID'), widget=BS3TextFieldWidget()
+            ),
+            "extra__azure_synapse__subscriptionId": StringField(
+                lazy_gettext('Subscription ID'), widget=BS3TextFieldWidget()
+            ),
+        }
+
+    @staticmethod
+    def get_ui_field_behaviour() -> Dict[str, Any]:
+        """Returns custom field behaviour"""
+        return {
+            "hidden_fields": ['schema', 'port', 'extra'],
+            "relabeling": {'login': 'Client ID', 'password': 'Secret', 'host': 
'Synapse Workspace URL'},
+        }
+
+    def __init__(self, azure_synapse_conn_id: str = default_conn_name, 
spark_pool: str = ''):
+        self._conn: Optional[SparkClient] = None
+        self.conn_id = azure_synapse_conn_id
+        self.spark_pool = spark_pool
+        super().__init__()
+
+    def get_conn(self) -> SparkClient:
+        if self._conn is not None:
+            return self._conn
+
+        conn = self.get_connection(self.conn_id)
+        tenant = conn.extra_dejson.get('extra__azure_synapse__tenantId')
+        spark_pool = self.spark_pool
+        livy_api_version = "2022-02-22-preview"
+
+        try:
+            subscription_id = 
conn.extra_dejson['extra__azure_synapse__subscriptionId']
+        except KeyError:
+            raise ValueError("A Subscription ID is required to connect to 
Azure Synapse.")
+
+        credential: Credentials
+        if conn.login is not None and conn.password is not None:
+            if not tenant:
+                raise ValueError("A Tenant ID is required when authenticating 
with Client ID and Secret.")
+
+            credential = ClientSecretCredential(
+                client_id=conn.login, client_secret=conn.password, 
tenant_id=tenant
+            )
+        else:
+            credential = DefaultAzureCredential()
+
+        self._conn = self._create_client(credential, conn.host, spark_pool, 
livy_api_version, subscription_id)
+
+        return self._conn
+
+    @staticmethod
+    def _create_client(credential: Credentials, host, spark_pool, 
livy_api_version, subscription_id: str):
+        return SparkClient(
+            credential=credential,
+            endpoint=host,
+            spark_pool_name=spark_pool,
+            livy_api_version=livy_api_version,
+            subscription_id=subscription_id,
+        )
+
+    def run_spark_job(
+        self,
+        payload: SparkBatchJobOptions,
+    ):
+        """
+        Run a job in an Apache Spark pool.
+
+        :param payload: Livy compatible payload which represents the spark job 
that a user wants to submit.
+        """
+        job = self.get_conn().spark_batch.create_spark_batch_job(payload)
+        self.job_id = job.id

Review Comment:
   Should `job_id` be an instance attr here? Looks like everywhere `job_id` is 
referenced it's an input arg.



##########
airflow/providers/microsoft/azure/operators/synapse.py:
##########
@@ -0,0 +1,105 @@
+# 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 typing import TYPE_CHECKING, Sequence
+
+from azure.synapse.spark.models import SparkBatchJobOptions
+
+from airflow.models import BaseOperator
+from airflow.providers.microsoft.azure.hooks.synapse import AzureSynapseHook, 
AzureSynapseSparkBatchRunStatus
+
+if TYPE_CHECKING:
+    from airflow.utils.context import Context
+
+
+class AzureSynapseRunSparkBatchOperator(BaseOperator):
+    """
+    Executes a Spark job on Azure Synapse.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the 
guide:
+        :ref:`howto/operator:AzureSynapseRunSparkBatchOperator`
+
+    :param azure_synapse_conn_id: The connection identifier for connecting to 
Azure Synapse.
+    :param wait_for_termination: Flag to wait on a job run's termination.
+    :param spark_pool: The target synapse spark pool used to submit the job
+    :param payload: Livy compatible payload which represents the spark job 
that a user wants to submit
+    :param timeout: Time in seconds to wait for a job to reach a terminal 
status for non-asynchronous
+        waits. Used only if ``wait_for_termination`` is True.
+    :param check_interval: Time in seconds to check on a job run's status for 
non-asynchronous waits.
+        Used only if ``wait_for_termination`` is True.
+    """
+
+    template_fields: Sequence[str] = (
+        "azure_synapse_conn_id",
+        "spark_pool",
+    )
+    template_fields_renderers = {"parameters": "json"}
+
+    ui_color = "#0678d4"
+
+    def __init__(
+        self,
+        *,
+        azure_synapse_conn_id: str = AzureSynapseHook.default_conn_name,
+        wait_for_termination: bool = True,
+        spark_pool: str = '',
+        payload: SparkBatchJobOptions,
+        timeout: int = 60 * 60 * 24 * 7,
+        check_interval: int = 60,
+        **kwargs,
+    ) -> None:
+        super().__init__(**kwargs)
+        self.azure_synapse_conn_id = azure_synapse_conn_id
+        self.wait_for_termination = wait_for_termination
+        self.spark_pool = spark_pool
+        self.payload = payload
+        self.timeout = timeout
+        self.check_interval = check_interval
+
+    def execute(self, context: "Context") -> None:
+        self.hook = AzureSynapseHook(
+            azure_synapse_conn_id=self.azure_synapse_conn_id, 
spark_pool=self.spark_pool
+        )
+        self.log.info("Executing the Synapse spark job.")
+        response = self.hook.run_spark_job(payload=self.payload)
+        self.log.info(response)
+        self.job_id = vars(response)["id"]
+        # Push the ``job_id`` value to XCom regardless of what happens during 
execution. This allows for
+        # retrieval the executed job's ``id`` for downstream tasks especially 
if performing an
+        # asynchronous wait.
+        context["ti"].xcom_push(key="job_id", value=self.job_id)
+
+        if self.wait_for_termination:
+            self.log.info("Waiting for job run %s to terminate.", self.job_id)
+
+            if self.hook.wait_for_job_run_status(
+                job_id=self.job_id,
+                expected_statuses=AzureSynapseSparkBatchRunStatus.SUCCESS,
+                check_interval=self.check_interval,
+                timeout=self.timeout,
+            ):
+                self.log.info("Job run %s has completed successfully.", 
self.job_id)
+            else:
+                raise Exception(f"Job run {self.job_id} has failed or has been 
cancelled.")
+
+    def on_kill(self) -> None:
+        if self.job_id:
+            self.hook.cancel_job_run(
+                job_id=self.job_id,
+            )
+            self.log.info("Job run %s has been cancelled successfully.", 
self.job_id)

Review Comment:
   WDYT about using the hooks `wait_for_job_run_status` method to confirm the 
job has reached a canceled state before logging that the job has been canceled?



##########
tests/system/providers/microsoft/azure/example_azure_synapse.py:
##########
@@ -0,0 +1,72 @@
+# 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 os
+from datetime import datetime, timedelta
+
+from airflow import DAG
+from airflow.providers.microsoft.azure.operators.synapse import 
AzureSynapseRunSparkBatchOperator
+
+AIRFLOW_HOME = os.getenv("AIRFLOW_HOME", "/usr/local/airflow")
+EXECUTION_TIMEOUT = int(os.getenv("EXECUTION_TIMEOUT", 6))
+
+default_args = {
+    "execution_timeout": timedelta(hours=EXECUTION_TIMEOUT),
+    "retries": int(os.getenv("DEFAULT_TASK_RETRIES", 2)),
+    "retry_delay": 
timedelta(seconds=int(os.getenv("DEFAULT_RETRY_DELAY_SECONDS", 60))),
+}
+
+SPARK_JOB_PAYLOAD = {
+    "name": "SparkJob",
+    "file": 
"abfss://[email protected]/wordcount.py",
+    "args": [
+        
"abfss://[email protected]/shakespeare.txt",
+        "abfss://[email protected]/results/",
+    ],
+    "jars": [],
+    "pyFiles": [],
+    "files": [],
+    "conf": {
+        "spark.dynamicAllocation.enabled": "false",
+        "spark.dynamicAllocation.minExecutors": "1",
+        "spark.dynamicAllocation.maxExecutors": "2",
+    },
+    "numExecutors": 2,
+    "executorCores": 4,
+    "executorMemory": "28g",
+    "driverCores": 4,
+    "driverMemory": "28g",
+}
+
+with DAG(
+    dag_id="example_synapse_spark_job",
+    start_date=datetime(2022, 1, 1),
+    schedule_interval=None,
+    catchup=False,
+    default_args=default_args,
+    tags=["example", "synapse"],
+) as dag:
+    # [START howto_operator_azure_synapse]
+    run_spark_job = AzureSynapseRunSparkBatchOperator(
+        task_id="run_spark_job", spark_pool="provsparkpool", 
payload=SPARK_JOB_PAYLOAD  # type: ignore

Review Comment:
   Just curious, what mypy error is being ignored here?



##########
airflow/providers/microsoft/azure/provider.yaml:
##########
@@ -115,6 +116,12 @@ integrations:
     how-to-guide:
       - /docs/apache-airflow-providers-microsoft-azure/operators/asb.rst
     tags: [azure]
+  - integration-name: Microsoft Azure Synapse
+    external-doc-url: https://azure.microsoft.com/en-us/services/service-bus/
+    logo: /integration-logos/azure/Service-Bus.svg
+    how-to-guide:
+      - /docs/apache-airflow-providers-microsoft-azure/operators/asb.rst

Review Comment:
   These are pointing to Azure Service Bus.



##########
tests/system/providers/microsoft/azure/example_azure_synapse.py:
##########
@@ -0,0 +1,72 @@
+# 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 os
+from datetime import datetime, timedelta
+
+from airflow import DAG
+from airflow.providers.microsoft.azure.operators.synapse import 
AzureSynapseRunSparkBatchOperator
+
+AIRFLOW_HOME = os.getenv("AIRFLOW_HOME", "/usr/local/airflow")
+EXECUTION_TIMEOUT = int(os.getenv("EXECUTION_TIMEOUT", 6))
+
+default_args = {
+    "execution_timeout": timedelta(hours=EXECUTION_TIMEOUT),
+    "retries": int(os.getenv("DEFAULT_TASK_RETRIES", 2)),
+    "retry_delay": 
timedelta(seconds=int(os.getenv("DEFAULT_RETRY_DELAY_SECONDS", 60))),
+}
+
+SPARK_JOB_PAYLOAD = {
+    "name": "SparkJob",
+    "file": 
"abfss://[email protected]/wordcount.py",
+    "args": [
+        
"abfss://[email protected]/shakespeare.txt",
+        "abfss://[email protected]/results/",
+    ],
+    "jars": [],
+    "pyFiles": [],
+    "files": [],
+    "conf": {
+        "spark.dynamicAllocation.enabled": "false",
+        "spark.dynamicAllocation.minExecutors": "1",
+        "spark.dynamicAllocation.maxExecutors": "2",
+    },
+    "numExecutors": 2,
+    "executorCores": 4,
+    "executorMemory": "28g",
+    "driverCores": 4,
+    "driverMemory": "28g",
+}
+
+with DAG(
+    dag_id="example_synapse_spark_job",
+    start_date=datetime(2022, 1, 1),
+    schedule_interval=None,

Review Comment:
   ```suggestion
       schedule=None,
   ```
   See #25410 and #25648



##########
docs/apache-airflow-providers-microsoft-azure/connections/azure_synapse.rst:
##########
@@ -0,0 +1,70 @@
+.. 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.
+
+
+
+.. _howto/connection:synapse:
+
+Microsoft Azure Synapse
+=======================
+
+The Microsoft Azure Synapse connection type enables the Azure Synapse 
Integrations.
+
+Authenticating to Azure Synapse
+-------------------------------
+
+There are multiple ways to connect to Azure Synapse using Airflow.
+
+1. Use `token credentials
+   
<https://docs.microsoft.com/en-us/azure/developer/python/azure-sdk-authenticate?tabs=cmd#authenticate-with-token-credentials>`_
+   i.e. add specific credentials (client_id, secret, tenant) and subscription 
id to the Airflow connection.
+2. Fallback on `DefaultAzureCredential
+   
<https://docs.microsoft.com/en-us/python/api/overview/azure/identity-readme?view=azure-python#defaultazurecredential>`_.
+   This includes a mechanism to try different options to authenticate: Managed 
System Identity, environment variables, authentication through Azure CLI...
+
+Default Connection IDs
+----------------------
+
+All hooks and operators related to Microsoft Azure Data Factory use 
``azure_synapse_default`` by default.
+
+Configuring the Connection
+--------------------------
+
+Client ID
+    Specify the ``client_id`` used for the initial connection.
+    This is needed for *token credentials* authentication mechanism.
+    It can be left out to fall back on ``DefaultAzureCredential``.
+
+Secret
+    Specify the ``secret`` used for the initial connection.
+    This is needed for *token credentials* authentication mechanism.
+    It can be left out to fall back on ``DefaultAzureCredential``.
+
+Tenant ID
+    Specify the Azure tenant ID used for the initial connection.
+    This is needed for *token credentials* authentication mechanism.
+    It can be left out to fall back on ``DefaultAzureCredential``.
+    Use the key ``extra__azure_synapse__tenantId`` to pass in the tenant ID.
+
+Subscription ID
+    Specify the ID of the subscription used for the initial connection.
+    This is needed for all authentication mechanisms.
+    Use the key ``extra__azure_synapse__subscriptionId`` to pass in the Azure 
subscription ID.
+
+Synapse Workspace URL
+    Specify the Azure Synapse endpoint to interface with.
+    If not specified in the connection, this needs to be passed in directly to 
hooks, operators, and sensors.

Review Comment:
   Is this statement true? Or was this supposed to be for the Spark pool param?



##########
tests/providers/microsoft/azure/hooks/test_azure_synapse.py:
##########
@@ -0,0 +1,186 @@
+# 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
+from typing import Type
+from unittest.mock import MagicMock, patch
+
+import pytest
+from azure.identity import ClientSecretCredential, DefaultAzureCredential
+from azure.synapse.spark import SparkClient
+from pytest import fixture
+
+from airflow.models.connection import Connection
+from airflow.providers.microsoft.azure.hooks.synapse import AzureSynapseHook, 
AzureSynapseSparkBatchRunStatus
+from airflow.utils import db
+
+DEFAULT_SPARK_POOL = "defaultSparkPool"
+
+DEFAULT_SYNAPSE = "defaultSynapse"
+SYNAPSE = "testSynapse"
+
+DEFAULT_CONNECTION_CLIENT_SECRET = "azure_synapse_test_client_secret"
+DEFAULT_CONNECTION_DEFAULT_CREDENTIAL = "azure_synapse_test_default_credential"
+
+MODEL = object()
+NAME = "testName"
+ID = "testId"
+JOB_ID = 1
+
+
+def setup_module():
+    connection_client_secret = Connection(
+        conn_id=DEFAULT_CONNECTION_CLIENT_SECRET,
+        conn_type="azure_synapse",
+        host="https://testsynapse.dev.azuresynapse.net";,
+        login="clientId",
+        password="clientSecret",
+        extra=json.dumps(
+            {
+                "extra__azure_synapse__tenantId": "tenantId",
+                "extra__azure_synapse__subscriptionId": "subscriptionId",
+                "extra__azure_synapse__spark_pool": DEFAULT_SPARK_POOL,

Review Comment:
   This connection param is missing from the hook (it's not an extra in the 
connection anyway) and custom connection spec. Should be added to the hook or 
removed from the connection here?



##########
docs/apache-airflow-providers-microsoft-azure/operators/azure_synapse.rst:
##########
@@ -0,0 +1,50 @@
+
+ .. 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.
+
+Azure Synapse Operators
+=======================
+Azure Synapse Analytics is a limitless analytics service that brings together 
data integration,
+enterprise data warehousing and big data analytics. It gives you the freedom 
to query data on your terms,
+using either serverless or dedicated options—at scale.
+Azure Synapse brings these worlds together with a unified experience to ingest,
+explore, prepare, transform, manage and serve data for immediate BI and 
machine learning needs.
+
+.. _howto/operator:AzureSynapseRunSparkBatchOperator:
+
+AzureSynapseRunSparkBatchOperator
+-----------------------------------
+Use the 
:class:`~airflow.providers.microsoft.azure.operators.synapse.AzureSynapseRunSparkBatchOperator`
 to execute a
+spark application within Synapse Analytics.
+By default, the operator will periodically check on the status of the executed 
Spark job to
+terminate with a "Succeeded" status.
+
+Below is an example of using this operator to execute a Spark application on 
Azure Synapse.
+
+  .. exampleinclude:: 
/../../tests/system/providers/microsoft/azure/example_adf_run_pipeline.py
+      :language: python
+      :dedent: 0

Review Comment:
   ```suggestion
     .. exampleinclude:: 
/../../tests/system/providers/microsoft/azure/example_azure_synapse.py
         :language: python
         :dedent: 4
   ```



##########
docs/apache-airflow-providers-microsoft-azure/connections/azure_synapse.rst:
##########
@@ -0,0 +1,70 @@
+.. 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.
+
+
+
+.. _howto/connection:synapse:
+
+Microsoft Azure Synapse
+=======================
+
+The Microsoft Azure Synapse connection type enables the Azure Synapse 
Integrations.
+
+Authenticating to Azure Synapse
+-------------------------------
+
+There are multiple ways to connect to Azure Synapse using Airflow.
+
+1. Use `token credentials
+   
<https://docs.microsoft.com/en-us/azure/developer/python/azure-sdk-authenticate?tabs=cmd#authenticate-with-token-credentials>`_
+   i.e. add specific credentials (client_id, secret, tenant) and subscription 
id to the Airflow connection.
+2. Fallback on `DefaultAzureCredential
+   
<https://docs.microsoft.com/en-us/python/api/overview/azure/identity-readme?view=azure-python#defaultazurecredential>`_.
+   This includes a mechanism to try different options to authenticate: Managed 
System Identity, environment variables, authentication through Azure CLI...
+
+Default Connection IDs
+----------------------
+
+All hooks and operators related to Microsoft Azure Data Factory use 
``azure_synapse_default`` by default.
+
+Configuring the Connection
+--------------------------
+
+Client ID
+    Specify the ``client_id`` used for the initial connection.
+    This is needed for *token credentials* authentication mechanism.
+    It can be left out to fall back on ``DefaultAzureCredential``.
+
+Secret
+    Specify the ``secret`` used for the initial connection.
+    This is needed for *token credentials* authentication mechanism.
+    It can be left out to fall back on ``DefaultAzureCredential``.
+
+Tenant ID
+    Specify the Azure tenant ID used for the initial connection.
+    This is needed for *token credentials* authentication mechanism.
+    It can be left out to fall back on ``DefaultAzureCredential``.
+    Use the key ``extra__azure_synapse__tenantId`` to pass in the tenant ID.
+
+Subscription ID

Review Comment:
   It might be a good idea to state in this doc that a subscription ID is 
required for the connection.



##########
docs/apache-airflow-providers-microsoft-azure/operators/azure_synapse.rst:
##########
@@ -0,0 +1,50 @@
+
+ .. 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.
+
+Azure Synapse Operators
+=======================
+Azure Synapse Analytics is a limitless analytics service that brings together 
data integration,
+enterprise data warehousing and big data analytics. It gives you the freedom 
to query data on your terms,
+using either serverless or dedicated options—at scale.
+Azure Synapse brings these worlds together with a unified experience to ingest,
+explore, prepare, transform, manage and serve data for immediate BI and 
machine learning needs.
+
+.. _howto/operator:AzureSynapseRunSparkBatchOperator:
+
+AzureSynapseRunSparkBatchOperator
+-----------------------------------
+Use the 
:class:`~airflow.providers.microsoft.azure.operators.synapse.AzureSynapseRunSparkBatchOperator`
 to execute a
+spark application within Synapse Analytics.
+By default, the operator will periodically check on the status of the executed 
Spark job to
+terminate with a "Succeeded" status.
+
+Below is an example of using this operator to execute a Spark application on 
Azure Synapse.
+
+  .. exampleinclude:: 
/../../tests/system/providers/microsoft/azure/example_azure_synapse.py
+      :language: python
+      :dedent: 0

Review Comment:
   ```suggestion
         :dedent: 4
   ```



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