-
Notifications
You must be signed in to change notification settings - Fork 54.3k
Expand file tree
/
Copy pathsystem_config.py
More file actions
464 lines (436 loc) · 16.5 KB
/
Copy pathsystem_config.py
File metadata and controls
464 lines (436 loc) · 16.5 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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
# -*- coding: utf-8 -*-
"""System configuration endpoints."""
from __future__ import annotations
import logging
import os
from fastapi import APIRouter, Depends, HTTPException, Query
from api.deps import get_system_config_service
from api.v1.schemas.common import ErrorResponse
from api.v1.schemas.system_config import (
DiscoverLLMChannelModelsRequest,
DiscoverLLMChannelModelsResponse,
ExportSystemConfigResponse,
ImportSystemConfigRequest,
SystemConfigConflictResponse,
SystemConfigResponse,
SystemConfigSchemaResponse,
SetupStatusResponse,
SystemConfigValidationErrorResponse,
TestLLMChannelRequest,
TestLLMChannelResponse,
TestNotificationChannelRequest,
TestNotificationChannelResponse,
UpdateSystemConfigRequest,
UpdateSystemConfigResponse,
ValidateSystemConfigRequest,
ValidateSystemConfigResponse,
)
from src.services.system_config_service import (
ConfigConflictError,
ConfigImportError,
ConfigValidationError,
SystemConfigService,
)
logger = logging.getLogger(__name__)
router = APIRouter()
def _ensure_desktop_mode() -> None:
"""Restrict desktop backup/restore endpoints to desktop runtime only."""
if os.getenv("DSA_DESKTOP_MODE", "").strip().lower() != "true":
raise HTTPException(
status_code=403,
detail={
"error": "desktop_only_feature",
"message": "This endpoint is only available in desktop mode",
},
)
@router.get(
"/config",
response_model=SystemConfigResponse,
responses={
200: {"description": "Configuration loaded"},
401: {"description": "Unauthorized", "model": ErrorResponse},
500: {"description": "Internal server error", "model": ErrorResponse},
},
summary="Get system configuration",
description="Read current configuration from .env and return raw values.",
)
def get_system_config(
include_schema: bool = Query(True, description="Whether to include schema metadata"),
service: SystemConfigService = Depends(get_system_config_service),
) -> SystemConfigResponse:
"""Load and return current system configuration."""
try:
payload = service.get_config(include_schema=include_schema)
return SystemConfigResponse.model_validate(payload)
except Exception as exc:
logger.error("Failed to load system configuration: %s", exc, exc_info=True)
raise HTTPException(
status_code=500,
detail={
"error": "internal_error",
"message": "Failed to load system configuration",
},
)
@router.get(
"/config/setup/status",
response_model=SetupStatusResponse,
responses={
200: {"description": "Setup status loaded"},
401: {"description": "Unauthorized", "model": ErrorResponse},
500: {"description": "Internal server error", "model": ErrorResponse},
},
summary="Get first-run setup status",
description="Read a side-effect-free setup readiness summary from saved and runtime configuration.",
)
def get_setup_status(
service: SystemConfigService = Depends(get_system_config_service),
) -> SetupStatusResponse:
"""Return first-run setup status without writing config or reloading runtime state."""
try:
payload = service.get_setup_status()
return SetupStatusResponse.model_validate(payload)
except Exception as exc:
logger.error("Failed to load setup status: %s", exc, exc_info=True)
raise HTTPException(
status_code=500,
detail={
"error": "internal_error",
"message": "Failed to load setup status",
},
)
@router.put(
"/config",
response_model=UpdateSystemConfigResponse,
responses={
200: {"description": "Configuration updated"},
400: {"description": "Validation failed", "model": SystemConfigValidationErrorResponse},
409: {"description": "Version conflict", "model": SystemConfigConflictResponse},
500: {"description": "Internal server error", "model": ErrorResponse},
},
summary="Update system configuration",
description="Update key-value pairs in .env. Mask token preserves existing secret values.",
)
def update_system_config(
request: UpdateSystemConfigRequest,
service: SystemConfigService = Depends(get_system_config_service),
) -> UpdateSystemConfigResponse:
"""Validate and persist system configuration updates."""
try:
payload = service.update(
config_version=request.config_version,
items=[item.model_dump() for item in request.items],
mask_token=request.mask_token,
reload_now=request.reload_now,
)
return UpdateSystemConfigResponse.model_validate(payload)
except ConfigValidationError as exc:
raise HTTPException(
status_code=400,
detail={
"error": "validation_failed",
"message": "System configuration validation failed",
"issues": exc.issues,
},
)
except ConfigConflictError as exc:
raise HTTPException(
status_code=409,
detail={
"error": "config_version_conflict",
"message": "Configuration has changed, please reload and retry",
"current_config_version": exc.current_version,
},
)
except Exception as exc:
logger.error("Failed to update system configuration: %s", exc, exc_info=True)
raise HTTPException(
status_code=500,
detail={
"error": "internal_error",
"message": "Failed to update system configuration",
},
)
@router.get(
"/config/export",
response_model=ExportSystemConfigResponse,
responses={
200: {"description": "Desktop env exported"},
401: {"description": "Unauthorized", "model": ErrorResponse},
403: {"description": "Desktop mode only", "model": ErrorResponse},
500: {"description": "Internal server error", "model": ErrorResponse},
},
summary="Export desktop env backup",
description="Desktop-only endpoint that returns the raw saved .env content.",
)
def export_desktop_system_config(
service: SystemConfigService = Depends(get_system_config_service),
) -> ExportSystemConfigResponse:
"""Export the active `.env` file for desktop backup."""
_ensure_desktop_mode()
try:
payload = service.export_desktop_env()
return ExportSystemConfigResponse.model_validate(payload)
except Exception as exc:
logger.error("Failed to export desktop system configuration: %s", exc, exc_info=True)
raise HTTPException(
status_code=500,
detail={
"error": "internal_error",
"message": "Failed to export desktop system configuration",
},
)
@router.post(
"/config/import",
response_model=UpdateSystemConfigResponse,
responses={
200: {"description": "Desktop env imported"},
400: {
"description": "Import failed",
"content": {
"application/json": {
"schema": {
"anyOf": [
{"$ref": "#/components/schemas/ErrorResponse"},
{"$ref": "#/components/schemas/SystemConfigValidationErrorResponse"},
]
}
}
},
},
401: {"description": "Unauthorized", "model": ErrorResponse},
403: {"description": "Desktop mode only", "model": ErrorResponse},
409: {"description": "Version conflict", "model": SystemConfigConflictResponse},
500: {"description": "Internal server error", "model": ErrorResponse},
},
summary="Import desktop env backup",
description="Desktop-only endpoint that merges raw .env text into the saved configuration.",
)
def import_desktop_system_config(
request: ImportSystemConfigRequest,
service: SystemConfigService = Depends(get_system_config_service),
) -> UpdateSystemConfigResponse:
"""Import a desktop `.env` backup into the active config."""
_ensure_desktop_mode()
try:
payload = service.import_desktop_env(
config_version=request.config_version,
content=request.content,
reload_now=request.reload_now,
)
return UpdateSystemConfigResponse.model_validate(payload)
except ConfigImportError as exc:
raise HTTPException(
status_code=400,
detail={
"error": "invalid_import_file",
"message": exc.message,
},
)
except ConfigValidationError as exc:
raise HTTPException(
status_code=400,
detail={
"error": "validation_failed",
"message": "System configuration validation failed",
"issues": exc.issues,
},
)
except ConfigConflictError as exc:
raise HTTPException(
status_code=409,
detail={
"error": "config_version_conflict",
"message": "Configuration has changed, please reload and retry",
"current_config_version": exc.current_version,
},
)
except Exception as exc:
logger.error("Failed to import desktop system configuration: %s", exc, exc_info=True)
raise HTTPException(
status_code=500,
detail={
"error": "internal_error",
"message": "Failed to import desktop system configuration",
},
)
@router.post(
"/config/validate",
response_model=ValidateSystemConfigResponse,
responses={
200: {"description": "Validation completed"},
500: {"description": "Internal server error", "model": ErrorResponse},
},
summary="Validate system configuration",
description="Validate submitted configuration values without writing to .env.",
)
def validate_system_config(
request: ValidateSystemConfigRequest,
service: SystemConfigService = Depends(get_system_config_service),
) -> ValidateSystemConfigResponse:
"""Run pre-save validation only."""
try:
payload = service.validate(items=[item.model_dump() for item in request.items])
return ValidateSystemConfigResponse.model_validate(payload)
except Exception as exc:
logger.error("Failed to validate system configuration: %s", exc, exc_info=True)
raise HTTPException(
status_code=500,
detail={
"error": "internal_error",
"message": "Failed to validate system configuration",
},
)
@router.post(
"/config/llm/test-channel",
response_model=TestLLMChannelResponse,
responses={
200: {"description": "Channel test completed"},
500: {"description": "Internal server error", "model": ErrorResponse},
},
summary="Test one LLM channel",
description="Run a minimal LLM request against one unsaved or saved channel definition.",
)
def test_llm_channel(
request: TestLLMChannelRequest,
service: SystemConfigService = Depends(get_system_config_service),
) -> TestLLMChannelResponse:
"""Validate and test one channel definition without writing `.env`."""
try:
payload = service.test_llm_channel(
name=request.name,
protocol=request.protocol,
base_url=request.base_url,
api_key=request.api_key,
models=request.models,
enabled=request.enabled,
timeout_seconds=request.timeout_seconds,
capability_checks=request.capability_checks,
)
return TestLLMChannelResponse.model_validate(payload)
except (ValueError, TypeError) as exc:
raise HTTPException(
status_code=422,
detail={
"error": "validation_error",
"message": str(exc),
},
)
except Exception as exc:
logger.error("Failed to test LLM channel: %s", exc, exc_info=True)
raise HTTPException(
status_code=500,
detail={
"error": "internal_error",
"message": "Failed to test LLM channel",
},
)
@router.post(
"/config/notification/test-channel",
response_model=TestNotificationChannelResponse,
responses={
200: {"description": "Notification channel test completed"},
500: {"description": "Internal server error", "model": ErrorResponse},
},
summary="Test one notification channel",
description="Send a short test notification using unsaved or saved notification configuration.",
)
def test_notification_channel(
request: TestNotificationChannelRequest,
service: SystemConfigService = Depends(get_system_config_service),
) -> TestNotificationChannelResponse:
"""Validate and test one notification channel without writing `.env`."""
try:
payload = service.test_notification_channel(
channel=request.channel,
items=[item.model_dump() for item in request.items],
mask_token=request.mask_token,
title=request.title,
content=request.content,
timeout_seconds=request.timeout_seconds,
)
return TestNotificationChannelResponse.model_validate(payload)
except (ValueError, TypeError) as exc:
raise HTTPException(
status_code=422,
detail={
"error": "validation_error",
"message": str(exc),
},
)
except Exception as exc:
logger.error("Failed to test notification channel: %s", exc, exc_info=True)
raise HTTPException(
status_code=500,
detail={
"error": "internal_error",
"message": "Failed to test notification channel",
},
)
@router.post(
"/config/llm/discover-models",
response_model=DiscoverLLMChannelModelsResponse,
responses={
200: {"description": "Model discovery completed"},
500: {"description": "Internal server error", "model": ErrorResponse},
},
summary="Discover models for one LLM channel",
description="Call one unsaved or saved channel's `/models` endpoint and return discovered model IDs.",
)
def discover_llm_channel_models(
request: DiscoverLLMChannelModelsRequest,
service: SystemConfigService = Depends(get_system_config_service),
) -> DiscoverLLMChannelModelsResponse:
"""Discover models for one channel definition without writing `.env`."""
try:
payload = service.discover_llm_channel_models(
name=request.name,
protocol=request.protocol,
base_url=request.base_url,
api_key=request.api_key,
models=request.models,
timeout_seconds=request.timeout_seconds,
)
return DiscoverLLMChannelModelsResponse.model_validate(payload)
except (ValueError, TypeError) as exc:
raise HTTPException(
status_code=422,
detail={
"error": "validation_error",
"message": str(exc),
},
)
except Exception as exc:
logger.error("Failed to discover LLM channel models: %s", exc, exc_info=True)
raise HTTPException(
status_code=500,
detail={
"error": "internal_error",
"message": "Failed to discover LLM channel models",
},
)
@router.get(
"/config/schema",
response_model=SystemConfigSchemaResponse,
responses={
200: {"description": "Schema loaded"},
500: {"description": "Internal server error", "model": ErrorResponse},
},
summary="Get system configuration schema",
description="Return categorized field metadata used for dynamic settings form rendering.",
)
def get_system_config_schema(
service: SystemConfigService = Depends(get_system_config_service),
) -> SystemConfigSchemaResponse:
"""Return schema metadata for system configuration fields."""
try:
payload = service.get_schema()
return SystemConfigSchemaResponse.model_validate(payload)
except Exception as exc:
logger.error("Failed to load system configuration schema: %s", exc, exc_info=True)
raise HTTPException(
status_code=500,
detail={
"error": "internal_error",
"message": "Failed to load system configuration schema",
},
)