-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathkernelRouter.py
More file actions
399 lines (365 loc) · 16.7 KB
/
Copy pathkernelRouter.py
File metadata and controls
399 lines (365 loc) · 16.7 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
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
from __future__ import annotations
from typing import Any
from fastapi import APIRouter, WebSocket
from ..kernel.executionPayload import executeKernelAll, executeKernelBlock, executeKernelReactive, previewKernelReactiveOrder
from ..kernel.protocol import (
CreateSessionRequest,
CreateSessionResponse,
ExecuteRequest,
UiEventRequest,
UiEventResponse,
)
from ..kernel.uiEventFlow import UiCallbackNotFound, handleKernelUiEvent, resetKernelUiCallbacks
from ..serverLog import formatLogFields, getServerLogger
from ..system.fileOps import MoveRequest, WorkspacePathError, WriteFileRequest
from ..system.packageOps import PackageEnvironmentError
from ..system.serverState import ServerState
from .errors import fail
from .kernelWebSocket import handleKernelWebSocket
from .requestModels import NotebookExecuteRequest, PackageRequest, PathRequest, ReactiveExecuteRequest, SetUiValueRequest
def createKernelRouter(state: ServerState) -> APIRouter:
router = APIRouter()
logger = getServerLogger()
def failWorkspaceBoundary(error: WorkspacePathError) -> None:
fail(403, "workspace_path_forbidden", str(error))
@router.post("/api/kernel/create", response_model=CreateSessionResponse)
def apiCreateSession(request: CreateSessionRequest | None = None) -> CreateSessionResponse:
workingDirectory = request.workingDirectory if request else None
session = state.sessionManager.createSession(workingDirectory=workingDirectory)
logger.info(
"kernel-session %s",
formatLogFields(
action="create",
sessionId=session.sessionId,
workingDirectory=workingDirectory,
totalSessions=state.sessionManager.sessionCount,
),
)
return CreateSessionResponse(sessionId=session.sessionId, status=session.status)
@router.get("/api/kernel/sessions")
def apiListSessions() -> list[dict[str, Any]]:
sessions = state.sessionManager.listSessions()
logger.debug("kernel-session %s", formatLogFields(action="list", totalSessions=len(sessions)))
return [session.model_dump() for session in sessions]
@router.post("/api/kernel/{sessionId}/execute")
async def apiExecute(sessionId: str, request: ExecuteRequest) -> dict[str, Any]:
session = requireSession(state, sessionId)
payload = await executeKernelBlock(session, request.code, blockId=request.blockId)
logger.debug(
"kernel-execute %s",
formatLogFields(
transport="http",
sessionId=sessionId,
blockId=request.blockId,
status=payload.result.status,
durationMs=payload.durationMs,
executionCount=payload.result.executionCount,
),
)
return payload.httpPayload()
@router.post("/api/kernel/{sessionId}/interrupt")
def apiInterrupt(sessionId: str) -> dict[str, Any]:
session = requireSession(state, sessionId)
result = session.interrupt()
interrupted = result.interrupted if hasattr(result, "interrupted") else bool(result)
logger.info(
"kernel-interrupt %s",
formatLogFields(sessionId=sessionId, interrupted=interrupted),
)
return {"interrupted": interrupted}
@router.get("/api/kernel/{sessionId}/variables")
def apiGetVariables(sessionId: str) -> list[dict[str, Any]]:
session = requireSession(state, sessionId)
variables = session.getVariables()
logger.debug(
"kernel-variables %s",
formatLogFields(transport="http", sessionId=sessionId, variableCount=len(variables)),
)
return [variable.model_dump() for variable in variables]
@router.post("/api/kernel/{sessionId}/reset")
def apiResetSession(sessionId: str) -> dict[str, str]:
session = requireSession(state, sessionId)
session.reset()
resetKernelUiCallbacks()
logger.info("kernel-reset %s", formatLogFields(sessionId=sessionId))
return {"status": "reset"}
@router.post("/api/kernel/{sessionId}/ui-event", response_model=UiEventResponse)
def apiUiEvent(sessionId: str, request: UiEventRequest) -> UiEventResponse:
session = requireSession(state, sessionId)
try:
response = handleKernelUiEvent(request, invoke=session.invokeUiCallback)
except (UiCallbackNotFound, KeyError):
logger.warning(
"ui-event %s",
formatLogFields(action="missing", sessionId=sessionId, callbackId=request.callbackId),
)
fail(404, "ui_callback_not_found", "UI callback not found.")
if response.status == "missing":
fail(404, "ui_callback_not_found", "UI callback not found.")
if response.status == "error":
logger.warning(
"ui-event %s",
formatLogFields(
action="error",
sessionId=sessionId,
callbackId=request.callbackId,
eventType=request.eventType,
error=response.error,
),
)
return response
logger.debug(
"ui-event %s",
formatLogFields(
action="invoke",
sessionId=sessionId,
callbackId=request.callbackId,
eventType=request.eventType,
blockId=request.blockId,
reactiveTriggerCount=len(response.reactiveTrigger),
),
)
return response
@router.delete("/api/kernel/{sessionId}")
def apiDestroySession(sessionId: str) -> dict[str, bool]:
destroyed = state.sessionManager.destroySession(sessionId)
log = logger.info if destroyed else logger.debug
log(
"kernel-session %s",
formatLogFields(
action="destroy" if destroyed else "already-destroyed",
sessionId=sessionId,
totalSessions=state.sessionManager.sessionCount,
),
)
return {"destroyed": destroyed}
@router.post("/api/kernel/{sessionId}/execute-reactive")
async def apiExecuteReactive(sessionId: str, request: ReactiveExecuteRequest) -> dict[str, Any]:
session = requireSession(state, sessionId)
blocks = [block.model_dump() for block in request.blocks]
payload = await executeKernelReactive(session, blocks, request.blockId, notebookName=request.notebookName)
logger.debug(
"kernel-reactive %s",
formatLogFields(
transport="http",
sessionId=sessionId,
changedBlockId=request.blockId,
resultCount=payload.resultCount,
executionCount=payload.executionCount,
durationMs=payload.durationMs,
),
)
return payload.httpPayload()
@router.post("/api/kernel/{sessionId}/execute-all")
async def apiExecuteAll(sessionId: str, request: NotebookExecuteRequest) -> dict[str, Any]:
session = requireSession(state, sessionId)
blocks = [block.model_dump() for block in request.blocks]
payload = await executeKernelAll(session, blocks, notebookName=request.notebookName)
logger.debug(
"kernel-execute-all %s",
formatLogFields(
transport="http",
sessionId=sessionId,
resultCount=payload.resultCount,
executionCount=payload.executionCount,
durationMs=payload.durationMs,
),
)
return payload.httpPayload()
@router.post("/api/kernel/{sessionId}/set-ui-value")
async def apiSetUiValue(sessionId: str, request: SetUiValueRequest) -> dict[str, Any]:
# 위젯 값 갱신 → 그 변수를 쓰는 다운스트림만 재실행(위젯 정의 셀 제외).
session = requireSession(state, sessionId)
session.setUiValue(request.elementId, request.value)
blocks = [block.model_dump() for block in request.blocks]
payload = await executeKernelReactive(session, blocks, request.blockId, includeSource=False)
logger.debug(
"kernel-reactive %s",
formatLogFields(
transport="http",
kind="setUiValue",
sessionId=sessionId,
changedBlockId=request.blockId,
elementId=request.elementId,
resultCount=payload.resultCount,
executionCount=payload.executionCount,
durationMs=payload.durationMs,
),
)
return payload.httpPayload()
@router.post("/api/kernel/reactive-preview")
def apiReactivePreview(request: ReactiveExecuteRequest) -> dict[str, Any]:
executionOrder = previewKernelReactiveOrder([block.model_dump() for block in request.blocks], request.blockId)
logger.debug(
"kernel-reactive %s",
formatLogFields(
transport="http",
mode="preview",
changedBlockId=request.blockId,
executionCount=len(executionOrder),
),
)
return {"executionOrder": executionOrder}
@router.post("/api/kernel/{sessionId}/remove-cell")
def apiRemoveCellDefinitions(sessionId: str, request: ExecuteRequest) -> dict[str, str]:
session = requireSession(state, sessionId)
session.removeCellDefinitions(request.blockId or "")
logger.debug(
"kernel-remove-definitions %s",
formatLogFields(sessionId=sessionId, blockId=request.blockId),
)
return {"status": "removed"}
@router.post("/api/kernel/{sessionId}/fs/list")
async def apiListSessionDirectory(sessionId: str, request: PathRequest) -> dict[str, Any]:
session = requireSession(state, sessionId)
try:
result = await session.getFiles(request.path)
logger.debug(
"kernel-fs %s",
formatLogFields(action="list", sessionId=sessionId, path=request.path, entryCount=len(result.entries)),
)
return result.model_dump()
except WorkspacePathError as error:
failWorkspaceBoundary(error)
@router.post("/api/kernel/{sessionId}/fs/read")
async def apiReadSessionFile(sessionId: str, request: PathRequest) -> dict[str, Any]:
session = requireSession(state, sessionId)
try:
content = await session.readFile(request.path)
logger.debug(
"kernel-fs %s",
formatLogFields(
action="read", sessionId=sessionId, path=request.path, contentLength=len(content.content)
),
)
return content.model_dump()
except WorkspacePathError as error:
failWorkspaceBoundary(error)
except FileNotFoundError:
fail(404, "file_not_found", "File not found.")
except UnicodeDecodeError:
fail(400, "file_not_text", "File is not a text file or has unsupported encoding.")
@router.post("/api/kernel/{sessionId}/fs/write")
async def apiWriteSessionFile(sessionId: str, request: WriteFileRequest) -> dict[str, str]:
session = requireSession(state, sessionId)
try:
resultPath = await session.writeFile(
request.path,
request.content,
encoding=request.encoding,
createDirectories=request.createDirectories,
)
logger.debug(
"kernel-fs %s",
formatLogFields(
action="write",
sessionId=sessionId,
path=resultPath,
contentLength=len(request.content),
createDirectories=request.createDirectories,
),
)
return {"path": resultPath}
except WorkspacePathError as error:
failWorkspaceBoundary(error)
@router.post("/api/kernel/{sessionId}/fs/delete")
async def apiDeleteSessionEntry(sessionId: str, request: PathRequest) -> dict[str, str]:
session = requireSession(state, sessionId)
try:
result = await session.deleteEntry(request.path)
logger.debug("kernel-fs %s", formatLogFields(action="delete", sessionId=sessionId, path=result))
return {"deleted": result}
except WorkspacePathError as error:
failWorkspaceBoundary(error)
except FileNotFoundError:
fail(404, "file_not_found", "File not found.")
@router.post("/api/kernel/{sessionId}/fs/move")
async def apiMoveSessionEntry(sessionId: str, request: MoveRequest) -> dict[str, str]:
session = requireSession(state, sessionId)
try:
result = await session.moveEntry(request.source, request.destination)
logger.debug(
"kernel-fs %s",
formatLogFields(
action="move",
sessionId=sessionId,
source=request.source,
destination=request.destination,
path=result,
),
)
return {"path": result}
except WorkspacePathError as error:
failWorkspaceBoundary(error)
except FileNotFoundError:
fail(404, "file_source_not_found", "Source not found.")
@router.post("/api/kernel/{sessionId}/fs/mkdir")
async def apiCreateSessionDirectory(sessionId: str, request: PathRequest) -> dict[str, str]:
session = requireSession(state, sessionId)
try:
result = await session.createDirectory(request.path)
logger.debug("kernel-fs %s", formatLogFields(action="mkdir", sessionId=sessionId, path=result))
return {"path": result}
except WorkspacePathError as error:
failWorkspaceBoundary(error)
@router.post("/api/kernel/{sessionId}/fs/exists")
async def apiSessionFileExists(sessionId: str, request: PathRequest) -> dict[str, bool]:
session = requireSession(state, sessionId)
try:
exists = await session.fileExists(request.path)
logger.debug(
"kernel-fs %s",
formatLogFields(action="exists", sessionId=sessionId, path=request.path, exists=exists),
)
return {"exists": exists}
except WorkspacePathError as error:
failWorkspaceBoundary(error)
@router.get("/api/kernel/{sessionId}/packages/list")
async def apiListSessionPackages(sessionId: str) -> list[dict[str, str]]:
session = requireSession(state, sessionId)
try:
packages = await session.listPackages()
logger.debug(
"kernel-packages %s",
formatLogFields(action="list", sessionId=sessionId, packageCount=len(packages)),
)
return [package.model_dump() for package in packages]
except PackageEnvironmentError as error:
fail(error.statusCode, error.code, error.message)
@router.post("/api/kernel/{sessionId}/packages/install")
async def apiInstallSessionPackage(sessionId: str, request: PackageRequest) -> dict[str, Any]:
session = requireSession(state, sessionId)
try:
result = await session.installPackage(request.name)
except PackageEnvironmentError as error:
fail(error.statusCode, error.code, error.message)
logger.info(
"kernel-packages %s",
formatLogFields(action="install", sessionId=sessionId, name=request.name, success=result.success),
)
return result.model_dump()
@router.post("/api/kernel/{sessionId}/packages/uninstall")
async def apiUninstallSessionPackage(sessionId: str, request: PackageRequest) -> dict[str, Any]:
session = requireSession(state, sessionId)
try:
result = await session.uninstallPackage(request.name)
except PackageEnvironmentError as error:
fail(error.statusCode, error.code, error.message)
logger.info(
"kernel-packages %s",
formatLogFields(action="uninstall", sessionId=sessionId, name=request.name, success=result.success),
)
return result.model_dump()
@router.websocket("/ws/kernel/{sessionId}")
async def kernelWebSocket(websocket: WebSocket, sessionId: str) -> None:
session = state.sessionManager.getSession(sessionId)
if session is None:
await websocket.close(code=4004, reason="Session not found.")
return
await handleKernelWebSocket(websocket, session, logger)
return router
def requireSession(state: ServerState, sessionId: str):
session = state.sessionManager.getSession(sessionId)
if session is None:
fail(404, "session_not_found", "Session not found.")
return session