Spaces:
Paused

File size: 8,725 Bytes
5a9484e
 
4405ca9
5eb4857
04b3d6d
5eb4857
 
6130eba
5eb4857
 
 
4405ca9
5eb4857
 
 
 
 
 
f3a0c24
 
a27a4ab
5eb4857
cbe40ee
5eb4857
 
 
 
 
1c89e32
5eb4857
f3a0c24
 
 
5eb4857
1c89e32
 
 
 
 
 
 
 
 
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a9484e
5eb4857
e58f87e
5eb4857
 
cbe40ee
5eb4857
 
 
 
 
 
 
 
 
cbe40ee
 
5eb4857
 
 
 
 
 
 
 
e58f87e
5eb4857
 
cbe40ee
73d8988
5eb4857
 
 
 
 
 
 
 
cbe40ee
 
5eb4857
73d8988
 
 
 
 
 
 
 
5eb4857
 
 
 
 
 
e58f87e
5eb4857
cbe40ee
 
5eb4857
 
 
 
 
 
 
 
 
bde564e
cbe40ee
5eb4857
 
b0867f8
 
 
 
 
 
 
 
cbe40ee
b0867f8
73d8988
b0867f8
 
 
 
 
 
 
 
 
 
 
 
 
cbe40ee
 
b0867f8
 
907d8c5
73d8988
 
 
 
 
b0867f8
 
 
cb0eb6e
b0867f8
 
 
 
 
 
 
 
8c5af7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d61e60f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from typing import Any, List, Dict, Optional
from uuid import UUID
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, cast, String
from datetime import datetime, timedelta
import time
from core.deps import get_db, get_current_staff_user, get_current_super_admin, get_arq_pool
from core.config import get_settings
from models.ai_workflow import AIWorkflow
from models.ai_interaction import AIInteraction
from models.meta_infra_health import MetaInfraHealth
from schemas.system import AIWorkflowRead, AIInteractionRead, MetaInfraHealthRead
from arq.connections import ArqRedis

router = APIRouter()
settings = get_settings()

from core.observability import check_infra_health

@router.get("/status/", dependencies=[Depends(get_current_super_admin)])
async def get_system_status(
    workspace_id: Optional[UUID] = None,
    db: AsyncSession = Depends(get_db),
    arq_pool: ArqRedis = Depends(get_arq_pool)
) -> Dict[str, Any]:
    """
    Aggregates real-time health metrics for the core infrastructure nodes.
    Calculates latency on-demand for accurate dashboard reporting.
    """
    # Use the unified health helper for DB and Redis
    infra_health = await check_infra_health(db, arq_pool)
    
    results = {
        "database": {
            "status": infra_health["database"], 
            "latency_ms": infra_health.get("database_latency", 0.0)
        },
        "redis": {
            "status": infra_health["redis"], 
            "latency_ms": infra_health.get("redis_latency", 0.0), 
            "pending_jobs": infra_health.get("pending_jobs", 0)
        },
        "ollama": {"status": "DOWN", "latency_ms": 0.0},
        "timestamp": datetime.utcnow()
    }

    # 3. Ollama Check
    start_time = time.perf_counter()
    try:
        import httpx
        async with httpx.AsyncClient(timeout=2.0) as client:
            resp = await client.get(f"{settings.OLLAMA_BASE_URL}/api/tags")
            if resp.status_code == 200:
                results["ollama"]["status"] = "UP"
                results["ollama"]["latency_ms"] = round((time.perf_counter() - start_time) * 1000, 2)
    except Exception:
        results["ollama"]["status"] = "DOWN"

    return results



@router.get("/workflows/", response_model=List[AIWorkflowRead], dependencies=[Depends(get_current_staff_user)])
async def get_recent_workflows(
    db: AsyncSession = Depends(get_db),
    workspace_id: Optional[UUID] = None,
    ticket_id: Optional[UUID] = None,
    offset: int = 0,
    limit: int = 20
) -> List[AIWorkflow]:
    """
    Retrieves AI workflows with optional ticket filtering and pagination.
    """
    stmt = select(AIWorkflow)
    
    if workspace_id:
        stmt = stmt.where(AIWorkflow.workspace_id == workspace_id)
    if ticket_id:
        stmt = stmt.where(AIWorkflow.entity_id == ticket_id)
        
    stmt = stmt.order_by(AIWorkflow.updated_at.desc()).offset(offset).limit(limit)
    
    result = await db.execute(stmt)
    return result.scalars().all()

@router.get("/interactions/", response_model=List[AIInteractionRead], dependencies=[Depends(get_current_staff_user)])
async def get_recent_interactions(
    db: AsyncSession = Depends(get_db),
    workspace_id: Optional[UUID] = None,
    ticket_id: Optional[str] = None,
    offset: int = 0,
    limit: int = 25
) -> List[AIInteraction]:
    """
    Retrieves granular AI interaction traces with optional ticket filtering and pagination.
    """
    stmt = select(AIInteraction)
    
    if workspace_id:
        stmt = stmt.where(AIInteraction.workspace_id == workspace_id)
    if ticket_id:
        # Support partial UUID match or exact UUID
        try:
            # Try exact UUID first
            t_uuid = UUID(ticket_id)
            stmt = stmt.where(AIInteraction.ticket_id == t_uuid)
        except ValueError:
            # Fallback to partial string match on the UUID column
            stmt = stmt.where(cast(AIInteraction.ticket_id, String).ilike(f"{ticket_id}%"))
        
    stmt = stmt.order_by(AIInteraction.created_at.desc()).offset(offset).limit(limit)
    
    result = await db.execute(stmt)
    return result.scalars().all()

@router.get("/history/", response_model=List[MetaInfraHealthRead], dependencies=[Depends(get_current_staff_user)])
async def get_performance_history(
    db: AsyncSession = Depends(get_db),
    workspace_id: Optional[UUID] = None
) -> List[MetaInfraHealth]:
    """
    Retrieves the last 24 hours of infrastructure health data.
    """
    since = datetime.utcnow() - timedelta(hours=24)
    stmt = (
        select(MetaInfraHealth)
        .where(MetaInfraHealth.created_at >= since)
    )
    # MetaInfraHealth is global, no workspace_id column
    stmt = stmt.order_by(MetaInfraHealth.created_at.asc())
    result = await db.execute(stmt)
    return result.scalars().all()

from models.audit_log import AuditLog
from models.user import User
from schemas.system import AuditLogRead

@router.get("/audit/", response_model=List[AuditLogRead], dependencies=[Depends(get_current_staff_user)])
async def get_security_audit_logs(
    db: AsyncSession = Depends(get_db),
    workspace_id: Optional[UUID] = None,
    entity_type: Optional[str] = None,
    entity_id: Optional[str] = None,
    action: Optional[str] = None,
    limit: int = 50,
    offset: int = 0
) -> Any:
    """
    Retrieves security and administrative audit logs.
    Hydrates the actor name for UI display.
    """
    stmt = (
        select(AuditLog, User.full_name)
        .outerjoin(User, AuditLog.user_id == User.id)
    )
    
    if workspace_id:
        stmt = stmt.where(AuditLog.workspace_id == workspace_id)
    if entity_type:
        stmt = stmt.where(AuditLog.entity_type == entity_type)
    if entity_id:
        try:
            e_uuid = UUID(entity_id)
            stmt = stmt.where(AuditLog.entity_id == e_uuid)
        except ValueError:
            stmt = stmt.where(cast(AuditLog.entity_id, String).ilike(f"{entity_id}%"))
    if action:
        stmt = stmt.where(AuditLog.action == action)
        
    stmt = stmt.order_by(AuditLog.created_at.desc()).offset(offset).limit(limit)
    result = await db.execute(stmt)
    logs = []
    for log_obj, actor_name in result.all():
        # Hydrate the virtual field
        setattr(log_obj, "actor_name", actor_name or "System/AI")
        logs.append(log_obj)
        
    return logs

@router.get("/diagnostics/redis/", dependencies=[Depends(get_current_super_admin)])
async def redis_diagnostics(arq_pool: ArqRedis = Depends(get_arq_pool)):
    """
    Superadmin-only diagnostic tool to inspect the state of the Arq/Redis backbone.
    """
    keys = []
    async for key in arq_pool.scan_iter("*"):
        keys.append(key.decode())
    
    # Category counts
    jobs = [k for k in keys if k.startswith("arq:job:")]
    health = [k for k in keys if k.startswith("arq:health-check")]
    latch = [k for k in keys if k.startswith("job_latch:")]
    
    return {
        "summary": {
            "total_keys": len(keys),
            "jobs_total": len(jobs),
            "workers_health_keys": len(health),
            "latches_total": len(latch)
        },
        "keys": keys[:200] # Return a sample
    }

from pydantic import BaseModel

class ManualTriageRequest(BaseModel):
    ticket_id: str

@router.post("/triage/", dependencies=[Depends(get_current_super_admin)])
async def manual_triage(
    req: ManualTriageRequest,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_super_admin)
):
    """
    Manually trigger a triage workflow for a ticket ID (exact or partial).
    """
    from agents.tools.nexus_tools import resolve_ticket_id
    from tasks.system import enqueue_task
    from fastapi import HTTPException
    
    role_str = str(current_user.role.value if hasattr(current_user.role, 'value') else current_user.role)
    ws_id = current_user.workspace_id or "00000000-0000-0000-0000-000000000000" # dummy if None, staff gets global fallback
    
    # Needs a dummy UUID if None, but since staff do global searches, it's fine.
    from uuid import UUID
    
    t_obj = await resolve_ticket_id(db, req.ticket_id, UUID(str(ws_id)), role=role_str)
    if not t_obj:
        raise HTTPException(status_code=404, detail=f"Ticket {req.ticket_id} not found or ambiguous.")
        
    actual_t_id, actual_ws_id = t_obj
    
    job_id = await enqueue_task("run_ai_workflow", actual_t_id, actual_ws_id, job_id=f"ai_workflow_manual_{actual_t_id}")
    
    if not job_id:
        raise HTTPException(status_code=500, detail="Failed to enqueue manual triage job.")
        
    return {"status": "success", "job_id": job_id, "ticket_id": actual_t_id}