File size: 4,644 Bytes
2021f39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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)