#!/usr/bin/env python3 """ Graph memory service with optional Neo4j, in-memory fallback. Endpoints: - GET /health - POST /upsert_nodes {nodes:[{id, labels, props}]} - POST /upsert_edges {edges:[{src, dst, type, props}]} - POST /neighbors {id, depth} """ import os from typing import Dict, Any, List, Set from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from prometheus_client import Counter, Histogram, make_asgi_app import uvicorn PORT = int(os.getenv("PORT", "7011")) # In-memory graph NODES: Dict[str, Dict[str, Any]] = {} EDGES: List[Dict[str, Any]] = [] ADJ: Dict[str, Set[str]] = {} app = FastAPI(title="Nova Graph Memory", version="0.1.0") app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) REQUESTS = Counter("graph_requests_total", "Graph service requests", ["route"]) LATENCY = Histogram("graph_request_latency_seconds", "Latency", ["route"]) @app.get("/health") def health(): REQUESTS.labels(route="health").inc() return {"status": "ok", "port": PORT} @app.post("/upsert_nodes") async def upsert_nodes(req: Request) -> JSONResponse: with LATENCY.labels(route="upsert_nodes").time(): REQUESTS.labels(route="upsert_nodes").inc() body = await req.json() nodes = body.get("nodes", []) # Optional Neo4j mirror neo_ok = False try: import os as _os from neo4j import GraphDatabase # type: ignore uri = _os.getenv("NEO4J_URI") if uri: driver = GraphDatabase.driver(uri, auth=(_os.getenv("NEO4J_USER", "neo4j"), _os.getenv("NEO4J_PASSWORD", "neo4j"))) neo_ok = True except Exception: driver = None for n in nodes: nid = str(n.get("id")) NODES[nid] = { "id": nid, "labels": n.get("labels", []), "props": n.get("props", {}), } ADJ.setdefault(nid, set()) if neo_ok: try: labels = ":" + ":".join(NODES[nid]["labels"]) if NODES[nid]["labels"] else "" props = NODES[nid]["props"] cypher = f"MERGE (n{labels} {{id:$id}}) SET n += $props" with driver.session() as s: s.run(cypher, id=nid, props=props) except Exception: pass return JSONResponse(status_code=200, content={"upserted": len(nodes)}) @app.post("/upsert_edges") async def upsert_edges(req: Request) -> JSONResponse: with LATENCY.labels(route="upsert_edges").time(): REQUESTS.labels(route="upsert_edges").inc() body = await req.json() edges = body.get("edges", []) for e in edges: src = str(e.get("src")) dst = str(e.get("dst")) etype = e.get("type", "REL") EDGES.append({"src": src, "dst": dst, "type": etype, "props": e.get("props", {})}) ADJ.setdefault(src, set()).add(dst) ADJ.setdefault(dst, set()) try: if neo_ok: cypher = "MERGE (a {id:$src}) MERGE (b {id:$dst}) MERGE (a)-[r:%s]->(b) SET r += $props" % etype with driver.session() as s: s.run(cypher, src=src, dst=dst, props=e.get("props", {})) except Exception: pass return JSONResponse(status_code=200, content={"upserted": len(edges)}) @app.post("/neighbors") async def neighbors(req: Request) -> JSONResponse: with LATENCY.labels(route="neighbors").time(): REQUESTS.labels(route="neighbors").inc() body = await req.json() start = str(body.get("id")) depth = int(body.get("depth", 1)) visited = set([start]) frontier = [start] hops = 0 order = [] while frontier and hops < depth: next_frontier = [] for nid in frontier: for nb in ADJ.get(nid, set()): if nb not in visited: visited.add(nb) next_frontier.append(nb) order.append(NODES.get(nb, {"id": nb})) frontier = next_frontier hops += 1 return JSONResponse(status_code=200, content={"neighbors": order}) # Prometheus metrics metrics_app = make_asgi_app() app.mount("/metrics", metrics_app) if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=PORT)