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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299 | def create_app() -> FastAPI:
""" Creates and returns the FastAPI application for the web editor.
"""
app = FastAPI(
lifespan=lifespan,
title="ayon_workflow.web_editor",
version=__version__,
description="AYON Workflow local web editor",
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/api/plugins", response_model=PluginsResponseModel)
async def get_plugins() -> PluginsResponseModel:
""" Get the list of node and dispatcher plugins.
"""
register_all_plugins()
registry = PluginRegistry()
return PluginsResponseModel(
plugins=[
PluginModel.from_plugin_desc(plugin_desc)
for plugin_desc in registry.plugin_list().values()
],
dispatchers=[
DispatchTaskModel.from_dispatch_task_cls(cls)
for cls in get_dispatch_node_types()
],
)
@app.post("/api/workflow/load", response_model=WorkflowLoadResponse)
async def workflow_load(
request: WorkflowLoadRequest,
) -> WorkflowLoadResponse:
""" Load a workflow JSON file from disk and return its contents.
"""
try:
workflow_content = load_workflow(request.path)
except FileNotFoundError as error:
raise HTTPException(status_code=404, detail=str(error))
except Exception as error:
raise HTTPException(status_code=400, detail=str(error))
return WorkflowLoadResponse(workflow=workflow_content)
@app.post("/api/workflow/save")
async def workflow_save(request: WorkflowSaveRequest):
""" Save a JSON workflow content as a file to disk.
"""
try:
save_workflow(request.path, request.workflow)
except Exception as error:
raise HTTPException(status_code=400, detail=str(error))
@app.post("/api/path-dialog", response_model=PathDialogResponse)
async def path_dialog(request: PathDialogRequest) -> PathDialogResponse:
""" Open a native OS file/directory dialog.
"""
loop = asyncio.get_running_loop()
path = await loop.run_in_executor(None, open_path_dialog, request)
return PathDialogResponse(path=path)
@app.post("/api/execute", response_model=ExecutionStatusResponse)
async def execute(request: ExecuteRequest) -> ExecutionStatusResponse:
""" Start a local in-process workflow execution.
"""
try:
register_all_plugins()
workflow = Workflow.from_dict(request.workflow)
except Exception as error:
raise HTTPException(status_code=400, detail=str(error))
try:
status = get_manager().start_execution(workflow)
except Exception as error:
raise HTTPException(status_code=400, detail=str(error))
return ExecutionStatusResponse(**status)
@app.post("/api/submit", response_model=ExecutionStatusResponse)
async def submit(request: SubmitRequest) -> ExecutionStatusResponse:
""" Submit a workflow to the render farm and start watching its output.
"""
try:
register_all_plugins()
workflow = Workflow.from_dict(request.workflow)
except Exception as error:
raise HTTPException(status_code=400, detail=str(error))
try:
# Dispatching can be time-consuming, this needs
# to run in executor to avoid blocking FastAPI event loop.
manager = get_manager()
status = await asyncio.get_running_loop().run_in_executor(
None,
lambda: manager.start_submit(
workflow,
backend_dir=request.backend_dir,
dispatch_graph_name=request.dispatch_graph_name,
project=request.project,
),
)
except Exception as error:
raise HTTPException(status_code=400, detail=str(error))
return ExecutionStatusResponse(**status)
@app.get(
"/api/execute/{run_id}",
response_model=ExecutionStatusResponse,
)
async def get_execution_status(run_id: int) -> ExecutionStatusResponse:
""" Get the status of a specific execution run.
"""
status = get_manager().get_status(run_id)
if status["status"] == "not_found":
raise HTTPException(status_code=404, detail="Run not found")
return ExecutionStatusResponse(**status)
@app.delete(
"/api/execute/{run_id}",
response_model=ExecutionStatusResponse,
)
async def cancel_execution(run_id: int) -> ExecutionStatusResponse:
""" Cancel the execution with the given run_id.
"""
manager = get_manager()
status = manager.get_status(run_id)
if status["status"] == "not_found":
raise HTTPException(status_code=404, detail="Run not found")
manager.cancel(run_id)
status = manager.get_status(run_id)
return ExecutionStatusResponse(**status)
@app.post("/api/shutdown")
async def shutdown():
""" Gracefully shut down the backend app.
"""
async def _deferred_shutdown():
# small delay to ensure response is transmitted first.
await asyncio.sleep(0.1)
os.kill(os.getpid(), signal.SIGTERM)
asyncio.create_task(_deferred_shutdown())
@app.websocket("/ws/execution/{run_id}")
async def execution_ws(
websocket: WebSocket,
run_id: int,
cursor: int = 0,
):
""" Stream execution events for a given run_id.
"""
# Accept websocket from client.
manager = get_manager()
queue = manager.get_queue(run_id)
await websocket.accept()
# Invalid run_id, close websocket with status not found.
if queue is None:
await websocket.send_json(
{
"event_type": "execution.end",
"run_id": run_id,
"execution_status": "not_found",
}
)
await websocket.close()
return
# Forward events from the run_id queue to the client web socket.
# This task runs in the background.
async def _forward_events(idx: int):
while True:
new_idx, events, closed = await asyncio.to_thread(
queue.get_from,
idx,
)
idx = new_idx # move cursor to the latest index.
for event in events:
await websocket.send_json(event)
if closed:
return
forward_task = asyncio.create_task(_forward_events(cursor))
# Listen for incoming cancellation from the client.
try:
while True:
msg = await websocket.receive_json()
if (
isinstance(msg, dict)
and msg.get("type") == "cancel"
and msg.get("run_id") == run_id
):
manager.cancel(run_id)
except WebSocketDisconnect:
pass # disconnection is fine, nothing to do
# Web socket is closed, cleanly or not.
# Cancel the forward task if it was still running.
finally:
forward_task.cancel()
with suppress(asyncio.CancelledError):
await forward_task
frontend_dir = get_frontend_dir()
if frontend_dir is not None:
index_html = frontend_dir / "index.html"
# Serve static files and SPA fallback in a single route.
# Static files (assets/...) are served directly; all other paths
# fall back to index.html for client-side routing.
@app.get("/{full_path:path}", include_in_schema=False)
async def spa_fallback(full_path: str) -> FileResponse:
file_path = frontend_dir / full_path
if file_path.is_file():
return FileResponse(file_path)
return FileResponse(index_html)
return app
|