-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvariables.py
More file actions
222 lines (180 loc) · 7.4 KB
/
variables.py
File metadata and controls
222 lines (180 loc) · 7.4 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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import os
import logging
import tempfile
import shutil
from typing import List
from polyapi.schema import map_primitive_types
from polyapi.typedefs import PropertyType, VariableSpecDto, Secrecy
from polyapi.utils import add_import_to_init, init_the_init
# GET is only included if the variable is not SECRET
GET_TEMPLATE = """
@staticmethod
def get() -> {variable_type}:
resp = variable_get("{variable_id}")
return resp.text
@staticmethod
async def get_async() -> {variable_type}:
resp = await variable_get_async("{variable_id}")
return resp.text
"""
TEMPLATE = """
from polyapi.poly.client_id import client_id
class {variable_name}:{get_method}
variable_id = "{variable_id}"
@staticmethod
def update(value: {variable_type}):
resp = variable_update("{variable_id}", value)
return resp.json()
@staticmethod
async def update_async(value: {variable_type}):
resp = await variable_update_async("{variable_id}", value)
return resp.json()
@classmethod
async def onUpdate(cls, callback):
api_key, base_url = get_api_key_and_url()
socket = socketio.AsyncClient()
await socket.connect(base_url, transports=['websocket'], namespaces=['/events'])
async def unregisterEventHandler():
# TODO
# socket.off("handleVariableChangeEvent:{variable_id}");
await socket.emit("unregisterVariableChangeEventHandler", {{
"clientID": client_id,
"variableId": cls.variable_id,
"apiKey": api_key,
}}, namespace='/events')
def registerCallback(registered):
if registered:
socket.on("handleVariableChangeEvent:{variable_id}", callback, namespace="/events")
await socket.emit("registerVariableChangeEventHandler", {{
"clientID": client_id,
"variableId": cls.variable_id,
"apiKey": api_key,
}}, namespace='/events', callback=registerCallback)
await socket.wait()
return unregisterEventHandler
@staticmethod
def inject(path=None) -> {variable_type}:
return {{
"type": "PolyVariable",
"id": "{variable_id}",
"path": path,
}} # type: ignore
"""
def generate_variables(variables: List[VariableSpecDto]):
failed_variables = []
for variable in variables:
try:
create_variable(variable)
except Exception as e:
variable_path = f"{variable.get('context', 'unknown')}.{variable.get('name', 'unknown')}"
variable_id = variable.get('id', 'unknown')
failed_variables.append(f"{variable_path} (id: {variable_id})")
logging.warning(f"WARNING: Failed to generate variable {variable_path} (id: {variable_id}): {str(e)}")
continue
if failed_variables:
logging.warning(f"WARNING: {len(failed_variables)} variable(s) failed to generate:")
for failed_var in failed_variables:
logging.warning(f" - {failed_var}")
def render_variable(variable: VariableSpecDto):
variable_type = _get_variable_type(variable["variable"]["valueType"])
# Only include get() method if secrecy is not SECRET
get_method = (
""
if variable["variable"]["secrecy"] == "SECRET"
else GET_TEMPLATE.format(
variable_id=variable["id"], variable_type=variable_type
)
)
return TEMPLATE.format(
variable_name=variable["name"],
variable_id=variable["id"],
variable_type=variable_type,
get_method=get_method,
)
def _get_variable_type(type_spec: PropertyType) -> str:
# simplified version of _get_type from api.py
if type_spec["kind"] == "plain":
value = type_spec["value"]
if value.endswith("[]"):
primitive = map_primitive_types(value[:-2])
return f"List[{primitive}]"
else:
return map_primitive_types(value)
elif type_spec["kind"] == "primitive":
return map_primitive_types(type_spec["type"])
elif type_spec["kind"] == "array":
return "List"
elif type_spec["kind"] == "void":
return "None"
elif type_spec["kind"] == "object":
return "Dict"
elif type_spec["kind"] == "any":
return "Any"
else:
return "Any"
def create_variable(variable: VariableSpecDto) -> None:
"""
Create a variable with atomic directory and file operations.
Tracks directory creation to enable cleanup on failure.
"""
folders = ["vari"]
if variable["context"]:
folders += variable["context"].split(".")
# build up the full_path by adding all the folders
full_path = os.path.join(os.path.dirname(os.path.abspath(__file__)))
created_dirs = [] # Track directories we create for cleanup on failure
try:
for idx, folder in enumerate(folders):
full_path = os.path.join(full_path, folder)
if not os.path.exists(full_path):
os.makedirs(full_path)
created_dirs.append(full_path) # Track for cleanup
next = folders[idx + 1] if idx + 1 < len(folders) else None
if next:
add_import_to_init(full_path, next)
add_variable_to_init(full_path, variable)
except Exception as e:
# Clean up directories we created (in reverse order)
for dir_path in reversed(created_dirs):
try:
if os.path.exists(dir_path) and not os.listdir(dir_path): # Only remove if empty
os.rmdir(dir_path)
except:
pass # Best effort cleanup
# Re-raise the original exception
raise e
def add_variable_to_init(full_path: str, variable: VariableSpecDto):
"""
Atomically add a variable to __init__.py to prevent partial corruption during generation failures.
This function generates all content first, then writes the file atomically using temporary files
to ensure that either the entire operation succeeds or no changes are made to the filesystem.
"""
try:
init_the_init(full_path)
init_path = os.path.join(full_path, "__init__.py")
# Generate variable content first
variable_content = render_variable(variable)
if not variable_content:
raise Exception("Variable rendering failed - empty content returned")
# Read current __init__.py content if it exists
init_content = ""
if os.path.exists(init_path):
with open(init_path, "r") as f:
init_content = f.read()
# Prepare new content to append
new_init_content = init_content + variable_content + "\n\n"
# Write to temporary file first, then atomic move
with tempfile.NamedTemporaryFile(mode="w", delete=False, dir=full_path, suffix=".tmp") as temp_file:
temp_file.write(new_init_content)
temp_file_path = temp_file.name
# Atomic operation: move temp file to final location
shutil.move(temp_file_path, init_path)
except Exception as e:
# Clean up temporary file if it exists
try:
if 'temp_file_path' in locals() and os.path.exists(temp_file_path):
os.unlink(temp_file_path)
except:
pass # Best effort cleanup
# Re-raise the original exception
raise e