-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwebhook.py
More file actions
152 lines (122 loc) · 4.77 KB
/
webhook.py
File metadata and controls
152 lines (122 loc) · 4.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import asyncio
import socketio # type: ignore
from socketio.exceptions import ConnectionError # type: ignore
import uuid
from typing import Any, Dict, List, Tuple
from polyapi.config import get_api_key_and_url
from polyapi.typedefs import PropertySpecification
from polyapi.utils import parse_arguments, poly_full_path, to_func_namespace
# all active webhook handlers, used by unregister_all to cleanup
active_handlers: List[Dict[str, Any]] = []
# global client shared by all webhooks, will be initialized by webhook.start
client = None
WEBHOOK_DEFS_TEMPLATE = """
from typing import List, Dict, Any, TypedDict, Callable
{function_args_def}
"""
WEBHOOK_TEMPLATE = """
async def {function_name}(
{function_args}
):
\"""{description}
Function ID: {function_id}
\"""
from polyapi.webhook import client, active_handlers
print("Starting webhook handler for {function_path}...")
if not client:
raise Exception("Client not initialized. Abort!")
options = options or {{}}
eventsClientId = "{client_id}"
function_id = "{function_id}"
api_key, base_url = get_api_key_and_url()
def registerCallback(registered: bool):
if registered:
client.on('handleWebhookEvent:{function_id}', handleEvent, namespace="/events")
else:
print("Could not set register webhook event handler for {function_id}")
async def handleEvent(data):
nonlocal api_key
nonlocal options
polyCustom = {{}}
resp = callback(data.get("body"), data.get("headers"), data.get("params"), polyCustom)
if options.get("waitForResponse"):
await client.emit('setWebhookListenerResponse', {{
"webhookHandleID": function_id,
"apiKey": api_key,
"clientID": eventsClientId,
"executionId": data.get("executionId"),
"response": {{
"data": resp,
"statusCode": polyCustom.get("responseStatusCode", 200),
"contentType": polyCustom.get("responseContentType", None),
}},
}}, namespace="/events")
data = {{
"clientID": eventsClientId,
"webhookHandleID": function_id,
"apiKey": api_key,
"waitForResponse": options.get("waitForResponse"),
}}
await client.emit('registerWebhookEventHandler', data, namespace="/events", callback=registerCallback)
active_handlers.append({{"clientID": eventsClientId, "webhookHandleID": function_id, "apiKey": api_key, "path": "{function_path}"}})
"""
async def get_client_and_connect():
_, base_url = get_api_key_and_url()
global client
client = socketio.AsyncClient()
await client.connect(base_url, transports=["websocket"], namespaces=["/events"])
async def unregister(data: Dict[str, Any]):
print(f"Stopping webhook handler for {data['path']}...")
assert client
await client.emit(
"unregisterWebhookEventHandler",
{
"clientID": data["clientID"],
"webhookHandleID": data["webhookHandleID"],
"apiKey": data["apiKey"],
},
"/events",
)
async def unregister_all():
_, base_url = get_api_key_and_url()
# maybe need to reconnect because maybe socketio client disconnected after Ctrl+C?
# feels like Linux disconnects but Windows stays connected
try:
await client.connect(base_url, transports=["websocket"], namespaces=["/events"])
except ConnectionError:
pass
await asyncio.gather(*[unregister(handler) for handler in active_handlers])
def render_webhook_handle(
function_type: str,
function_context: str,
function_name: str,
function_id: str,
function_description: str,
arguments: List[PropertySpecification],
return_type: Dict[str, Any],
) -> Tuple[str, str]:
function_args, function_args_def = parse_arguments(function_name, arguments)
if "WebhookEventType" in function_args:
# let's add the function name import!
function_args = function_args.replace("WebhookEventType", f"{to_func_namespace(function_name)}.WebhookEventType")
func_str = WEBHOOK_TEMPLATE.format(
description=function_description,
client_id=uuid.uuid4().hex,
function_id=function_id,
function_name=function_name,
function_args=function_args,
function_path=poly_full_path(function_context, function_name),
)
func_defs = WEBHOOK_DEFS_TEMPLATE.format(function_args_def=function_args_def)
return func_str, func_defs
def start(*args):
loop = asyncio.get_event_loop()
loop.run_until_complete(get_client_and_connect())
asyncio.gather(*args)
try:
loop.run_forever()
except KeyboardInterrupt:
pass
finally:
loop.run_until_complete(unregister_all())
loop.stop()