|
| 1 | +from datetime import timedelta |
| 2 | +from typing import Any, Dict, Optional, Type, Union |
| 3 | + |
| 4 | +from flytekit import Documentation |
| 5 | +from flytekit.configuration import SerializationSettings |
| 6 | +from flytekit.core.base_task import PythonTask |
| 7 | +from flytekit.extend.backend.base_agent import SyncAgentExecutorMixin |
| 8 | + |
| 9 | +from ...core.interface import Interface |
| 10 | +from .constants import DATA_KEY, HEADERS_KEY, METHOD_KEY, SHOW_DATA_KEY, SHOW_URL_KEY, TASK_TYPE, TIMEOUT_SEC, URL_KEY |
| 11 | + |
| 12 | + |
| 13 | +class WebhookTask(SyncAgentExecutorMixin, PythonTask): |
| 14 | + """ |
| 15 | + The WebhookTask is used to invoke a webhook. The webhook can be invoked with a POST or GET method. |
| 16 | +
|
| 17 | + All the parameters can be formatted using python format strings. |
| 18 | +
|
| 19 | + Example: |
| 20 | + ```python |
| 21 | + simple_get = WebhookTask( |
| 22 | + name="simple-get", |
| 23 | + url="http://localhost:8000/", |
| 24 | + method=http.HTTPMethod.GET, |
| 25 | + headers={"Content-Type": "application/json"}, |
| 26 | + ) |
| 27 | +
|
| 28 | + get_with_params = WebhookTask( |
| 29 | + name="get-with-params", |
| 30 | + url="http://localhost:8000/items/{inputs.item_id}", |
| 31 | + method=http.HTTPMethod.GET, |
| 32 | + headers={"Content-Type": "application/json"}, |
| 33 | + dynamic_inputs={"s": str, "item_id": int}, |
| 34 | + show_data=True, |
| 35 | + show_url=True, |
| 36 | + description="Test Webhook Task", |
| 37 | + data={"q": "{inputs.s}"}, |
| 38 | + ) |
| 39 | +
|
| 40 | +
|
| 41 | + @fk.workflow |
| 42 | + def wf(s: str) -> (dict, dict, dict): |
| 43 | + v = hello(s=s) |
| 44 | + w = WebhookTask( |
| 45 | + name="invoke-slack", |
| 46 | + url="https://hooks.slack.com/services/xyz/zaa/aaa", |
| 47 | + headers={"Content-Type": "application/json"}, |
| 48 | + data={"text": "{inputs.s}"}, |
| 49 | + show_data=True, |
| 50 | + show_url=True, |
| 51 | + description="Test Webhook Task", |
| 52 | + dynamic_inputs={"s": str}, |
| 53 | + ) |
| 54 | + return simple_get(), get_with_params(s=v, item_id=10), w(s=v) |
| 55 | + ``` |
| 56 | +
|
| 57 | + All the parameters can be formatted using python format strings. The following parameters are available for |
| 58 | + formatting: |
| 59 | + - dynamic_inputs: These are the dynamic inputs to the task. The keys are the names of the inputs and the values |
| 60 | + are the values of the inputs. All inputs are available under the prefix `inputs.`. |
| 61 | + For example, if the inputs are {"input1": 10, "input2": "hello"}, then you can |
| 62 | + use {inputs.input1} and {inputs.input2} in the URL and the body. Define the dynamic_inputs argument in the |
| 63 | + constructor to use these inputs. The dynamic inputs should not be actual values, but the types of the inputs. |
| 64 | +
|
| 65 | + TODO Coming soon secrets support |
| 66 | + - secrets: These are the secrets that are requested by the task. The keys are the names of the secrets and the |
| 67 | + values are the values of the secrets. All secrets are available under the prefix `secrets.`. |
| 68 | + For example, if the secret requested are Secret(name="secret1") and Secret(name="secret), then you can use |
| 69 | + {secrets.secret1} and {secrets.secret2} in the URL and the body. Define the secret_requests argument in the |
| 70 | + constructor to use these secrets. The secrets should not be actual values, but the types of the secrets. |
| 71 | +
|
| 72 | + :param name: Name of this task, should be unique in the project |
| 73 | + :param url: The endpoint or URL to invoke for this webhook. This can be a static string or a python format string, |
| 74 | + where the format arguments are the dynamic_inputs to the task, secrets etc. Refer to the description for more |
| 75 | + details of available formatting parameters. |
| 76 | + :param method: The HTTP method to use for the request. Default is POST. |
| 77 | + :param headers: The headers to send with the request. This can be a static dictionary or a python format string, |
| 78 | + where the format arguments are the dynamic_inputs to the task, secrets etc. Refer to the description for more |
| 79 | + details of available formatting parameters. |
| 80 | + :param data: The body to send with the request. This can be a static dictionary or a python format string, |
| 81 | + where the format arguments are the dynamic_inputs to the task, secrets etc. Refer to the description for more |
| 82 | + details of available formatting parameters. the data should be a json serializable dictionary and will be |
| 83 | + sent as the json body of the POST request and as the query parameters of the GET request. |
| 84 | + :param dynamic_inputs: The dynamic inputs to the task. The keys are the names of the inputs and the values |
| 85 | + are the types of the inputs. These inputs are available under the prefix `inputs.` to be used in the URL, |
| 86 | + headers and body and other formatted fields. |
| 87 | + :param secret_requests: The secrets that are requested by the task. (TODO not yet supported) |
| 88 | + :param show_data: If True, the body of the request will be logged in the UI as the output of the task. |
| 89 | + :param show_url: If True, the URL of the request will be logged in the UI as the output of the task. |
| 90 | + :param description: Description of the task |
| 91 | + :param timeout: The timeout for the request (connection and read). Default is 10 seconds. If int value is provided, |
| 92 | + it is considered as seconds. |
| 93 | + """ |
| 94 | + |
| 95 | + def __init__( |
| 96 | + self, |
| 97 | + name: str, |
| 98 | + url: str, |
| 99 | + method: str = "POST", |
| 100 | + headers: Optional[Dict[str, str]] = None, |
| 101 | + data: Optional[Dict[str, Any]] = None, |
| 102 | + dynamic_inputs: Optional[Dict[str, Type]] = None, |
| 103 | + show_data: bool = False, |
| 104 | + show_url: bool = False, |
| 105 | + description: Optional[str] = None, |
| 106 | + timeout: Union[int, timedelta] = timedelta(seconds=10), |
| 107 | + # secret_requests: Optional[List[Secret]] = None, TODO Secret support is coming soon |
| 108 | + ): |
| 109 | + if method not in {"GET", "POST"}: |
| 110 | + raise ValueError(f"Method should be either GET or POST. Got {method}") |
| 111 | + |
| 112 | + interface = Interface( |
| 113 | + inputs=dynamic_inputs or {}, |
| 114 | + outputs={"info": dict}, |
| 115 | + ) |
| 116 | + super().__init__( |
| 117 | + name=name, |
| 118 | + interface=interface, |
| 119 | + task_type=TASK_TYPE, |
| 120 | + # secret_requests=secret_requests, |
| 121 | + docs=Documentation(short_description=description) if description else None, |
| 122 | + ) |
| 123 | + self._url = url |
| 124 | + self._method = method |
| 125 | + self._headers = headers |
| 126 | + self._data = data |
| 127 | + self._show_data = show_data |
| 128 | + self._show_url = show_url |
| 129 | + self._timeout_sec = timeout if isinstance(timeout, int) else timeout.total_seconds() |
| 130 | + |
| 131 | + def get_custom(self, settings: SerializationSettings) -> Dict[str, Any]: |
| 132 | + config = { |
| 133 | + URL_KEY: self._url, |
| 134 | + METHOD_KEY: self._method, |
| 135 | + HEADERS_KEY: self._headers or {}, |
| 136 | + DATA_KEY: self._data or {}, |
| 137 | + SHOW_DATA_KEY: self._show_data, |
| 138 | + SHOW_URL_KEY: self._show_url, |
| 139 | + TIMEOUT_SEC: self._timeout_sec, |
| 140 | + } |
| 141 | + return config |
0 commit comments