<% ' ApiGraphController: entities, typed relationships and bounded traversal (spec FR-023, section 8.1, section 14, ' ADR-014). Stateless JSON API, no layout. Helpers: core/lib.Graph.asp, core/lib.Learning.asp (evidence). ' ' POST /api/v1/entities CreateEntity {"namespace_id","type","name","canonical_key","aliases":[],"description","properties":{}} ' GET /api/v1/entities Entities ?namespace_id= &type= &q= &limit= ' GET /api/v1/entities/:id Entity ' PATCH /api/v1/entities/:id UpdateEntity {"name","aliases","description","properties"} (canonical key and type are fixed) ' DELETE /api/v1/entities/:id DeleteEntity also deletes every relationship touching it ' POST /api/v1/relate Relate {"namespace_id","source":{"kind","id"},"target":{"kind","id"},"type", ' "description","confidence","valid_from","valid_until","inferred", ' "evidence":[{"kind","id","role","excerpt"}]} -> proposed ' GET /api/v1/relationships Relationships ?namespace_id= &state= &type= &node_kind= &node_id= &limit= ' GET /api/v1/relationships/:id Relationship with its evidence ' POST /api/v1/relationships/:id/review Review {"decision":"accept|reject","notes"} ' DELETE /api/v1/relationships/:id DeleteRelationship ' POST /api/v1/graph/traverse Traverse {"start":{"kind","id"},"direction":"out|in|both","max_depth":2, ' "max_nodes":50,"types":[],"include_proposed":false} ' ' Kinds of endpoints: entity, memory, document. Relationship types are upper-case words (IS_A, PART_OF, DEPENDS_ON, ' IMPLEMENTS, CALLS, SOLVES, CONTRADICTS, SUPERSEDES, VERIFIED_BY, RELATES_TO, or another of the same form). ' Permissions on the namespace: write (CreateEntity, UpdateEntity, Relate; Relate also needs read on both endpoints), ' read (lists, fetches, Traverse), verify (Review; the author needs admin), delete (DeleteEntity, DeleteRelationship). ' An edge is visible only when the edge's namespace and both endpoints are readable; otherwise it does not exist for ' the caller (404, or simply left out). Traversal follows accepted edges that are valid now, skips retired memories ' and is bounded by depth, node and edge limits. Class ApiGraphController_Class Private m_errs Public Property Get useLayout() useLayout = False End Property Public Property Let useLayout(v) End Property Public Property Get Title() Title = "Graph API" End Property '--------------------------------------------------------------- ' POST /api/v1/entities '--------------------------------------------------------------- Public Sub CreateEntity() Dim body, input, nsId, eType, name, cKey, aliases, descr, props, rs, existing, entId, ts, k If Not Api_Authenticate() Then Exit Sub body = Api_ReadBody() If IsEmpty(body) Then Exit Sub Set input = JsonLite_Parse(body) m_errs = "" nsId = ReqString(input, "namespace_id", 64) eType = LCase("" & ReqString(input, "type", 40)) name = ReqString(input, "name", 200) cKey = OptString(input, "canonical_key", 200) aliases = AliasesJson(input) descr = OptString(input, "description", 2000) props = ObjectJson(input, "properties") If Len(eType) > 0 Then If Not IsEntityType(eType) Then AddErr "type must be 1 to 40 characters: lower-case letters, digits, '_' or '-', starting with a letter." End If End If If IsNull(cKey) Then cKey = Graph_CanonicalKey(name) Else cKey = Graph_CanonicalKey(cKey) If Len(cKey) = 0 Then AddErr "canonical_key must not be empty." End If End If If Len(m_errs) > 0 Then Api_Invalid Split(m_errs, Chr(30)) Exit Sub End If If Not Api_CanAccessNamespace(nsId, "write") Then Api_Audit "entity.create", "namespace", nsId, "denied" Api_Error 404, "namespace_not_found", "Namespace not found." Exit Sub End If Set rs = DAL().Query("SELECT id FROM entities WHERE namespace_id = ? AND type = ? AND canonical_key = ?", Array(nsId, eType, cKey)) existing = "" If Not rs.EOF Then existing = "" & rs(0) End If rs.Close If Len(existing) > 0 Then Api_Send 409, "{""error"":{""code"":""entity_exists"",""message"":""An entity with this type and canonical key already exists in the namespace."",""existing_id"":" & _ JsonLite_Quote(existing) & ",""request_id"":" & JsonLite_Quote(Api_RequestId()) & "}}" Exit Sub End If entId = Api_NewId() ts = Api_Now() On Error Resume Next DAL().BeginTransaction DAL().Execute "INSERT INTO entities (id, tenant_id, namespace_id, type, canonical_key, name, created_by, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, '" & ts & "')", _ Array(entId, Api_TenantId, nsId, eType, cKey, name, Api_PrincipalId, ts) DAL().Execute "UPDATE entities SET aliases = ?, description = ?, properties = ? WHERE id = ?", Array(aliases, descr, props, entId) If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError DAL().RollbackTransaction Api_DbFailed k, "" Exit Sub End If DAL().CommitTransaction If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Api_DbFailed k, "" Exit Sub End If On Error GoTo 0 Api_Audit "entity.create", "entity", entId, "ok" Response.AddHeader "Location", "/api/v1/entities/" & entId Api_Send 201, "{""data"":" & EntityById(entId) & "}" End Sub '--------------------------------------------------------------- ' GET /api/v1/entities '--------------------------------------------------------------- Public Sub Entities() Dim allowed, nsFilter, eType, q, limit, sql, params, rs, out, n, pat If Not Api_Authenticate() Then Exit Sub nsFilter = Trim("" & Request.QueryString("namespace_id")) eType = LCase(Trim("" & Request.QueryString("type"))) q = Trim("" & Request.QueryString("q")) limit = Api_ToInt(Request.QueryString("limit"), 50, 1, 200) If Len(nsFilter) > 0 Then If Not Api_IsId(nsFilter) Then Api_Invalid Array("namespace_id must be a valid id.") Exit Sub End If End If If Len(eType) > 0 Then If Not IsEntityType(eType) Then Api_Invalid Array("type is not a valid entity type.") Exit Sub End If End If If Len(q) > 200 Then Api_Invalid Array("q must be at most 200 characters.") Exit Sub End If allowed = Api_AllowedNamespaceIds("read") out = "" n = 0 If Len(allowed) > 0 Then sql = EntitySelect() & " WHERE tenant_id = ? AND namespace_id IN (" & allowed & ")" If Len(nsFilter) > 0 Then sql = sql & " AND namespace_id = '" & nsFilter & "'" End If If Len(eType) > 0 Then sql = sql & " AND type = '" & eType & "'" End If If Len(q) > 0 Then ' name, canonical key or an alias contains q ('!' escapes LIKE wildcards) pat = "%" & Replace(Replace(Replace(LCase(q), "!", "!!"), "%", "!%"), "_", "!_") & "%" sql = sql & " AND (LOWER(name) LIKE ? ESCAPE '!' OR canonical_key LIKE ? ESCAPE '!' OR LOWER(COALESCE(aliases, '')) LIKE ? ESCAPE '!')" params = Array(Api_TenantId, pat, pat, pat) Else params = Api_TenantId End If Set rs = DAL().Query(sql & " ORDER BY name, id LIMIT " & limit, params) Do While Not rs.EOF If n > 0 Then out = out & "," End If out = out & EntityJson(rs) n = n + 1 rs.MoveNext Loop rs.Close End If Api_Send 200, "{""data"":[" & out & "]}" End Sub '--------------------------------------------------------------- ' GET /api/v1/entities/:id '--------------------------------------------------------------- Public Sub Entity(id) Dim nsId If Not Api_Authenticate() Then Exit Sub nsId = Graph_NodeNamespace("entity", id) If Len(nsId) = 0 Then Api_NotFound Exit Sub End If If Not Api_CanAccessNamespace(nsId, "read") Then Api_NotFound Exit Sub End If Api_Send 200, "{""data"":" & EntityById(id) & "}" End Sub '--------------------------------------------------------------- ' PATCH /api/v1/entities/:id '--------------------------------------------------------------- Public Sub UpdateEntity(id) Dim body, input, nsId, sets, vals, name, aliases, descr, props, k, i, params If Not Api_Authenticate() Then Exit Sub nsId = Graph_NodeNamespace("entity", id) If Len(nsId) = 0 Then Api_NotFound Exit Sub End If If Not Api_CanAccessNamespace(nsId, "write") Then Api_Audit "entity.update", "entity", id, "denied" Api_NotFound Exit Sub End If body = Api_ReadBody() If IsEmpty(body) Then Exit Sub Set input = JsonLite_Parse(body) m_errs = "" sets = "" vals = "" If input.Exists("canonical_key") Or input.Exists("type") Or input.Exists("namespace_id") Then AddErr "type, canonical_key and namespace_id cannot be changed; create a new entity instead." End If If input.Exists("name") Then name = ReqString(input, "name", 200) sets = sets & "name = ?, " vals = vals & Chr(30) & "name" End If If input.Exists("aliases") Then aliases = AliasesJson(input) sets = sets & "aliases = ?, " vals = vals & Chr(30) & "aliases" End If If input.Exists("description") Then descr = OptString(input, "description", 2000) sets = sets & "description = ?, " vals = vals & Chr(30) & "description" End If If input.Exists("properties") Then props = ObjectJson(input, "properties") sets = sets & "properties = ?, " vals = vals & Chr(30) & "properties" End If If Len(m_errs) = 0 Then If Len(sets) = 0 Then AddErr "Nothing to change: give name, aliases, description or properties." End If End If If Len(m_errs) > 0 Then Api_Invalid Split(m_errs, Chr(30)) Exit Sub End If vals = Split(Mid(vals, 2), Chr(30)) ReDim params(UBound(vals) + 2) For i = 0 To UBound(vals) Select Case vals(i) Case "name" params(i) = name Case "aliases" params(i) = aliases Case "description" params(i) = descr Case "properties" params(i) = props End Select Next params(UBound(vals) + 1) = Api_Now() params(UBound(vals) + 2) = id On Error Resume Next DAL().Execute "UPDATE entities SET " & sets & "updated_at = ? WHERE id = ?", params If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Api_DbFailed k, "" Exit Sub End If On Error GoTo 0 Api_Audit "entity.update", "entity", id, "ok" Api_Send 200, "{""data"":" & EntityById(id) & "}" End Sub '--------------------------------------------------------------- ' DELETE /api/v1/entities/:id '--------------------------------------------------------------- Public Sub DeleteEntity(id) Dim nsId, k If Not Api_Authenticate() Then Exit Sub nsId = Graph_NodeNamespace("entity", id) If Len(nsId) = 0 Then Api_NotFound Exit Sub End If If Not Api_CanAccessNamespace(nsId, "delete") Then Api_Audit "entity.delete", "entity", id, "denied" Api_NotFound Exit Sub End If On Error Resume Next DAL().BeginTransaction Graph_ForgetNode "entity", id DAL().Execute "DELETE FROM entities WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId) If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError DAL().RollbackTransaction Api_DbFailed k, "" Exit Sub End If DAL().CommitTransaction If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Api_DbFailed k, "" Exit Sub End If On Error GoTo 0 Api_Audit "entity.delete", "entity", id, "ok" Api_Send 200, "{""deleted"":true,""id"":" & JsonLite_Quote(id) & "}" End Sub '--------------------------------------------------------------- ' POST /api/v1/relate '--------------------------------------------------------------- Public Sub Relate() Dim body, input, idemKey, reqHash, nsId, sKind, sId, tKind, tId, rType, descr, confidence, vFrom, vUntil, inferred Dim ev, msg, rs, relId, ts, resp, k, ns2 If Not Api_Authenticate() Then Exit Sub body = Api_ReadBody() If IsEmpty(body) Then Exit Sub Set input = JsonLite_Parse(body) idemKey = Api_Header("Idempotency-Key") If Len(idemKey) > 200 Then Api_Error 400, "invalid_idempotency_key", "Idempotency-Key must be at most 200 characters." Exit Sub End If reqHash = Api_Sha256("relate|" & body) If Not Api_IdempotencyGate(idemKey, reqHash) Then Exit Sub m_errs = "" nsId = ReqString(input, "namespace_id", 64) ReadEndpoint input, "source", sKind, sId ReadEndpoint input, "target", tKind, tId rType = UCase("" & ReqString(input, "type", 40)) descr = OptString(input, "description", 2000) confidence = OptUnit(input, "confidence") vFrom = OptTimestamp(input, "valid_from") vUntil = OptTimestamp(input, "valid_until") inferred = 0 If input.Exists("inferred") Then If VarType(input.Item("inferred")) = vbBoolean Then If input.Item("inferred") Then inferred = 1 End If ElseIf Not IsNull(input.Item("inferred")) Then AddErr "inferred must be true or false." End If End If If Len(rType) > 0 Then If Not Graph_IsType(rType) Then AddErr "type must be 2 to 40 characters: letters, digits or '_', starting with a letter (for example DEPENDS_ON)." End If End If If Not IsNull(vFrom) Then If Not IsNull(vUntil) Then If vUntil <= vFrom Then AddErr "valid_until must be later than valid_from." End If End If End If If Len(sId) > 0 Then If sKind = tKind And sId = tId Then AddErr "source and target must be different." End If End If If Len(m_errs) > 0 Then Api_Invalid Split(m_errs, Chr(30)) Exit Sub End If If Not Api_CanAccessNamespace(nsId, "write") Then Api_Audit "relationship.propose", "namespace", nsId, "denied" Api_Error 404, "namespace_not_found", "Namespace not found." Exit Sub End If ' Both endpoints must exist in this tenant and be readable; an unreadable one is reported like a missing one. ns2 = Graph_NodeNamespace(sKind, sId) If Len(ns2) > 0 Then If Not Api_CanAccessNamespace(ns2, "read") Then ns2 = "" End If End If If Len(ns2) = 0 Then Api_Invalid Array("source was not found.") Exit Sub End If ns2 = Graph_NodeNamespace(tKind, tId) If Len(ns2) > 0 Then If Not Api_CanAccessNamespace(ns2, "read") Then ns2 = "" End If End If If Len(ns2) = 0 Then Api_Invalid Array("target was not found.") Exit Sub End If Set ev = New Evidence_Class msg = ev.Load(input, "evidence") If Len(msg) > 0 Then Api_Invalid Array(msg) Exit Sub End If If ev.Count = 0 Then Api_Invalid Array("evidence must contain at least one item: graph assertions need evidence.") Exit Sub End If Set rs = DAL().Query("SELECT id, state FROM relationships WHERE namespace_id = ? AND source_kind = ? AND source_id = ? AND target_kind = ? AND target_id = ? AND type = ? " & _ "AND state IN ('proposed','accepted')", Array(nsId, sKind, sId, tKind, tId, rType)) If Not rs.EOF Then resp = "{""error"":{""code"":""relationship_exists"",""message"":""This relationship is already " & rs(1) & " in the namespace."",""existing_id"":" & _ JsonLite_Quote("" & rs(0)) & ",""request_id"":" & JsonLite_Quote(Api_RequestId()) & "}}" rs.Close Api_Send 409, resp Exit Sub End If rs.Close relId = Api_NewId() ts = Api_Now() resp = "{""id"":" & JsonLite_Quote(relId) & ",""state"":""proposed"",""namespace_id"":" & JsonLite_Quote(nsId) & ",""type"":" & JsonLite_Quote(rType) & _ ",""source"":" & NodeRef(sKind, sId) & ",""target"":" & NodeRef(tKind, tId) & ",""evidence_count"":" & ev.Count & "}" On Error Resume Next DAL().BeginTransaction ' NOT NULL author and time are server values (a principal id from the database and Api_Now), inlined because ' G3DB takes at most 8 parameters DAL().Execute "INSERT INTO relationships (id, tenant_id, namespace_id, source_kind, source_id, target_kind, target_id, type, author_principal_id, created_at) " & _ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, '" & Api_PrincipalId & "', '" & ts & "')", Array(relId, Api_TenantId, nsId, sKind, sId, tKind, tId, rType) DAL().Execute "UPDATE relationships SET description = ?, confidence = ?, valid_from = ?, valid_until = ?, inferred = " & inferred & " WHERE id = ?", _ Array(descr, confidence, vFrom, vUntil, relId) ev.Save "relationship", relId, Null Api_IdempotencyStore idemKey, reqHash, 201, resp If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError DAL().RollbackTransaction Api_DbFailed k, "" Exit Sub End If DAL().CommitTransaction If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Api_DbFailed k, "" Exit Sub End If On Error GoTo 0 Api_Audit "relationship.propose", "relationship", relId, "ok" Response.AddHeader "Location", "/api/v1/relationships/" & relId Api_Send 201, resp End Sub '--------------------------------------------------------------- ' GET /api/v1/relationships '--------------------------------------------------------------- Public Sub Relationships() Dim allowed, nsFilter, state, rType, nKind, nId, limit, sql, rs, out, n If Not Api_Authenticate() Then Exit Sub nsFilter = Trim("" & Request.QueryString("namespace_id")) state = LCase(Trim("" & Request.QueryString("state"))) rType = UCase(Trim("" & Request.QueryString("type"))) nKind = LCase(Trim("" & Request.QueryString("node_kind"))) nId = Trim("" & Request.QueryString("node_id")) limit = Api_ToInt(Request.QueryString("limit"), 50, 1, 200) m_errs = "" If Len(nsFilter) > 0 Then If Not Api_IsId(nsFilter) Then AddErr "namespace_id must be a valid id." End If End If If Len(state) > 0 Then If state <> "proposed" And state <> "accepted" And state <> "rejected" Then AddErr "state must be proposed, accepted or rejected." End If End If If Len(rType) > 0 Then If Not Graph_IsType(rType) Then AddErr "type is not a valid relationship type." End If End If If Len(nKind) > 0 Or Len(nId) > 0 Then If Not Graph_IsKind(nKind) Then AddErr "node_kind must be entity, memory or document (with node_id)." ElseIf Not Api_IsId(nId) Then AddErr "node_id must be a valid id (with node_kind)." End If End If If Len(m_errs) > 0 Then Api_Invalid Split(m_errs, Chr(30)) Exit Sub End If allowed = Api_AllowedNamespaceIds("read") out = "" n = 0 If Len(allowed) > 0 Then sql = RelSelect() & " WHERE r.tenant_id = ? AND r.namespace_id IN (" & allowed & ") AND " & _ Graph_NodeVisibleSql("source", allowed, False) & " AND " & Graph_NodeVisibleSql("target", allowed, False) If Len(nsFilter) > 0 Then sql = sql & " AND r.namespace_id = '" & nsFilter & "'" End If If Len(state) > 0 Then sql = sql & " AND r.state = '" & state & "'" End If If Len(rType) > 0 Then sql = sql & " AND r.type = '" & rType & "'" End If If Len(nKind) > 0 Then sql = sql & " AND ((r.source_kind = '" & nKind & "' AND r.source_id = '" & nId & "') OR (r.target_kind = '" & nKind & "' AND r.target_id = '" & nId & "'))" End If Set rs = DAL().Query(sql & " ORDER BY r.created_at DESC, r.id LIMIT " & limit, Api_TenantId) Do While Not rs.EOF If n > 0 Then out = out & "," End If out = out & RelJson(rs) n = n + 1 rs.MoveNext Loop rs.Close End If Api_Send 200, "{""data"":[" & out & "]}" End Sub '--------------------------------------------------------------- ' GET /api/v1/relationships/:id '--------------------------------------------------------------- Public Sub Relationship(id) Dim json If Not Api_Authenticate() Then Exit Sub json = VisibleRelJson(id, "read") If Len(json) = 0 Then Api_NotFound Exit Sub End If json = Left(json, Len(json) - 1) & ",""evidence"":" & Evidence_Json("relationship", id, Null) & "}" Api_Send 200, "{""data"":" & json & "}" End Sub '--------------------------------------------------------------- ' POST /api/v1/relationships/:id/review '--------------------------------------------------------------- Public Sub Review(id) Dim body, input, rs, nsId, state, author, decision, notes, k, newState If Not Api_Authenticate() Then Exit Sub If Len(VisibleRelJson(id, "verify")) = 0 Then Api_Audit "relationship.review", "relationship", id, "denied" Api_NotFound Exit Sub End If body = Api_ReadBody() If IsEmpty(body) Then Exit Sub Set input = JsonLite_Parse(body) Set rs = DAL().Query("SELECT namespace_id, state, author_principal_id FROM relationships WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) If rs.EOF Then rs.Close Api_NotFound Exit Sub End If nsId = "" & rs(0) state = "" & rs(1) author = "" & rs(2) rs.Close m_errs = "" decision = LCase("" & ReqString(input, "decision", 20)) notes = OptString(input, "notes", 2000) If Len(m_errs) = 0 Then If decision <> "accept" And decision <> "reject" Then AddErr "decision must be accept or reject." End If End If If Len(m_errs) > 0 Then Api_Invalid Split(m_errs, Chr(30)) Exit Sub End If If state <> "proposed" Then Api_Error 409, "relationship_already_reviewed", "The relationship was already " & state & "." Exit Sub End If If author = Api_PrincipalId Then If Not Api_CanAccessNamespace(nsId, "admin") Then Api_Audit "relationship.review", "relationship", id, "self_review_denied" Api_Error 403, "self_review_not_allowed", "A relationship cannot be reviewed by its author without admin permission on the namespace." Exit Sub End If End If newState = "rejected" If decision = "accept" Then newState = "accepted" End If On Error Resume Next DAL().Execute "UPDATE relationships SET state = ?, reviewer_principal_id = ?, review_notes = ?, reviewed_at = ? WHERE id = ? AND state = 'proposed'", _ Array(newState, Api_PrincipalId, notes, Api_Now(), id) If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Api_DbFailed k, "" Exit Sub End If On Error GoTo 0 Api_Audit "relationship.review", "relationship", id, newState Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""state"":" & JsonLite_Quote(newState) & "}" End Sub '--------------------------------------------------------------- ' DELETE /api/v1/relationships/:id '--------------------------------------------------------------- Public Sub DeleteRelationship(id) Dim k If Not Api_Authenticate() Then Exit Sub If Len(VisibleRelJson(id, "delete")) = 0 Then Api_Audit "relationship.delete", "relationship", id, "denied" Api_NotFound Exit Sub End If On Error Resume Next DAL().BeginTransaction DAL().Execute "DELETE FROM evidence_links WHERE owner_kind = 'relationship' AND owner_id = ?", id DAL().Execute "DELETE FROM relationships WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId) If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError DAL().RollbackTransaction Api_DbFailed k, "" Exit Sub End If DAL().CommitTransaction If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Api_DbFailed k, "" Exit Sub End If On Error GoTo 0 Api_Audit "relationship.delete", "relationship", id, "ok" Api_Send 200, "{""deleted"":true,""id"":" & JsonLite_Quote(id) & "}" End Sub '--------------------------------------------------------------- ' POST /api/v1/graph/traverse '--------------------------------------------------------------- Public Sub Traverse() Dim body, input, sKind, sId, direction, maxDepth, maxNodes, types, includeProposed, startNs, allowed Dim baseSql, typeSql, arr, i, nowTs, visited, seenEdges, frontier, nextFrontier, depth, frontierSet Dim cond, rs, rows, j, eid, srcKey, tgtKey, oKind, oId, oKey, nodes, edges, nodeCount, edgeCount, truncated, stopAll If Not Api_Authenticate() Then Exit Sub body = Api_ReadBody() If IsEmpty(body) Then Exit Sub Set input = JsonLite_Parse(body) m_errs = "" ReadEndpoint input, "start", sKind, sId direction = "both" If input.Exists("direction") Then direction = LCase("" & input.Item("direction")) If direction <> "out" And direction <> "in" And direction <> "both" Then AddErr "direction must be out, in or both." End If End If maxDepth = OptInt(input, "max_depth", 2, 1, GRAPH_MAX_DEPTH) maxNodes = OptInt(input, "max_nodes", 50, 1, GRAPH_MAX_NODES) includeProposed = False If input.Exists("include_proposed") Then If VarType(input.Item("include_proposed")) = vbBoolean Then includeProposed = input.Item("include_proposed") ElseIf Not IsNull(input.Item("include_proposed")) Then AddErr "include_proposed must be true or false." End If End If typeSql = "" If input.HasRaw("types") Then arr = JsonLite_ParseStringArray(input.Raw("types")) If IsNull(arr) Then AddErr "types must be an array of strings." ElseIf UBound(arr) > 19 Then AddErr "types may contain at most 20 entries." Else For i = 0 To UBound(arr) If Not Graph_IsType(UCase(Trim(arr(i)))) Then AddErr "types[" & i & "] is not a valid relationship type." Exit For End If If Len(typeSql) > 0 Then typeSql = typeSql & "," End If typeSql = typeSql & "'" & UCase(Trim(arr(i))) & "'" Next End If ElseIf input.Exists("types") Then If Not IsNull(input.Item("types")) Then AddErr "types must be an array of strings." End If End If If Len(m_errs) > 0 Then Api_Invalid Split(m_errs, Chr(30)) Exit Sub End If startNs = Graph_NodeNamespace(sKind, sId) If Len(startNs) > 0 Then If Not Api_CanAccessNamespace(startNs, "read") Then startNs = "" End If End If If Len(startNs) = 0 Then Api_NotFound Exit Sub End If allowed = Api_AllowedNamespaceIds("read") ' Edges the caller may see: readable edge namespace, both endpoints readable (retired memories left out, ' except the start node itself), accepted (or proposed on request), valid now, of the requested types. nowTs = Api_Now() baseSql = RelSelect() & " WHERE r.tenant_id = ? AND r.namespace_id IN (" & allowed & ")" If includeProposed Then baseSql = baseSql & " AND r.state IN ('accepted','proposed')" Else baseSql = baseSql & " AND r.state = 'accepted'" End If baseSql = baseSql & " AND (r.valid_from IS NULL OR r.valid_from <= '" & nowTs & "') AND (r.valid_until IS NULL OR r.valid_until > '" & nowTs & "')" If Len(typeSql) > 0 Then baseSql = baseSql & " AND r.type IN (" & typeSql & ")" End If baseSql = baseSql & " AND (" & Graph_NodeVisibleSql("source", allowed, True) & " OR (r.source_kind = '" & sKind & "' AND r.source_id = '" & sId & "'))" & _ " AND (" & Graph_NodeVisibleSql("target", allowed, True) & " OR (r.target_kind = '" & sKind & "' AND r.target_id = '" & sId & "'))" visited = "|" & sKind & ":" & sId & "|" seenEdges = "|" frontier = sKind & ":" & sId nodes = NodeJson(sKind, sId, 0) edges = "" nodeCount = 1 edgeCount = 0 truncated = False stopAll = False For depth = 1 To maxDepth If Len(frontier) = 0 Or stopAll Then Exit For End If frontierSet = "|" & Replace(frontier, Chr(30), "|") & "|" cond = "" If direction <> "in" Then cond = FrontierSql("source", frontier) End If If direction <> "out" Then If Len(cond) > 0 Then cond = cond & " OR " End If cond = cond & FrontierSql("target", frontier) End If Set rs = DAL().Query(baseSql & " AND (" & cond & ") ORDER BY r.created_at, r.id LIMIT " & (GRAPH_MAX_EDGES + 1), Api_TenantId) rows = Empty If Not rs.EOF Then rows = rs.GetRows() End If rs.Close nextFrontier = "" If Not IsEmpty(rows) Then For j = 0 To UBound(rows, 2) eid = "" & rows(0, j) If InStr(seenEdges, "|" & eid & "|") = 0 Then srcKey = rows(2, j) & ":" & rows(3, j) tgtKey = rows(4, j) & ":" & rows(5, j) oKey = "" If direction <> "in" Then If InStr(frontierSet, "|" & srcKey & "|") > 0 Then oKind = "" & rows(4, j) oId = "" & rows(5, j) oKey = tgtKey End If End If If Len(oKey) = 0 Then If direction <> "out" Then If InStr(frontierSet, "|" & tgtKey & "|") > 0 Then oKind = "" & rows(2, j) oId = "" & rows(3, j) oKey = srcKey End If End If End If If Len(oKey) > 0 Then If edgeCount >= GRAPH_MAX_EDGES Then truncated = True stopAll = True Exit For End If If InStr(visited, "|" & oKey & "|") = 0 Then If nodeCount >= maxNodes Then truncated = True oKey = "" Else nodes = nodes & "," & NodeJson(oKind, oId, depth) nodeCount = nodeCount + 1 visited = visited & oKey & "|" If Len(nextFrontier) > 0 Then nextFrontier = nextFrontier & Chr(30) End If nextFrontier = nextFrontier & oKey End If End If End If If Len(oKey) > 0 Then seenEdges = seenEdges & eid & "|" If edgeCount > 0 Then edges = edges & "," End If edges = edges & RelJsonRow(rows, j) edgeCount = edgeCount + 1 End If End If Next End If frontier = nextFrontier Next Api_Send 200, "{""start"":" & NodeRef(sKind, sId) & ",""direction"":" & JsonLite_Quote(direction) & ",""max_depth"":" & maxDepth & _ ",""nodes"":[" & nodes & "],""edges"":[" & edges & "],""truncated"":" & LCase(CStr(truncated)) & "}" End Sub '--------------------------------------------------------------- ' Helpers '--------------------------------------------------------------- ' "(r._kind = 'k' AND r._id IN (...)) OR ..." for the frontier keys ("kind:id" joined by Chr(30)); ' kinds and ids come from the database and were validated, so inlining them is safe. Private Function FrontierSql(side, frontier) Dim keys, kinds, k, i, ids, out, p keys = Split(frontier, Chr(30)) kinds = Array("entity", "memory", "document") out = "" For k = 0 To 2 ids = "" For i = 0 To UBound(keys) p = InStr(keys(i), ":") If Left(keys(i), p - 1) = kinds(k) Then If Api_IsId(Mid(keys(i), p + 1)) Then If Len(ids) > 0 Then ids = ids & "," End If ids = ids & "'" & Mid(keys(i), p + 1) & "'" End If End If Next If Len(ids) > 0 Then If Len(out) > 0 Then out = out & " OR " End If out = out & "(r." & side & "_kind = '" & kinds(k) & "' AND r." & side & "_id IN (" & ids & "))" End If Next If Len(out) = 0 Then out = "1 = 0" End If FrontierSql = "(" & out & ")" End Function ' The relationship as JSON when the caller holds perm on its namespace and can read both endpoints, else "". Private Function VisibleRelJson(id, perm) Dim rs, json, nsId, ok, sKind, sId, tKind, tId VisibleRelJson = "" If Not Api_IsId(id) Then Exit Function End If Set rs = DAL().Query(RelSelect() & " WHERE r.id = ? AND r.tenant_id = ?", Array(id, Api_TenantId)) If rs.EOF Then rs.Close Exit Function End If nsId = "" & rs(1) json = RelJson(rs) sKind = "" & rs(2) sId = "" & rs(3) tKind = "" & rs(4) tId = "" & rs(5) rs.Close ok = EndpointReadable(sKind, sId) If ok Then ok = EndpointReadable(tKind, tId) End If If Not ok Then Exit Function End If If Not Api_CanAccessNamespace(nsId, perm) Then Exit Function End If If perm <> "read" Then ' Write-type permissions do not imply read in grants: the caller must also be able to see the edge. If Not Api_CanAccessNamespace(nsId, "read") Then Exit Function End If End If VisibleRelJson = json End Function Private Function EndpointReadable(kind, id) Dim ns EndpointReadable = False ns = Graph_NodeNamespace(kind, id) If Len(ns) > 0 Then EndpointReadable = Api_CanAccessNamespace(ns, "read") End If End Function Private Function RelSelect() RelSelect = "SELECT r.id, r.namespace_id, r.source_kind, r.source_id, r.target_kind, r.target_id, r.type, r.description, r.confidence, " & _ "r.valid_from, r.valid_until, r.inferred, r.state, r.author_principal_id, r.reviewer_principal_id, r.review_notes, r.created_at, r.reviewed_at FROM relationships r" End Function Private Function RelJson(rs) Dim v, i ReDim v(17) For i = 0 To 17 v(i) = rs(i) Next RelJson = RelJsonValues(v) End Function Private Function RelJsonRow(rows, j) Dim v, i ReDim v(17) For i = 0 To 17 v(i) = rows(i, j) Next RelJsonRow = RelJsonValues(v) End Function Private Function RelJsonValues(v) RelJsonValues = "{""id"":" & JsonLite_Quote("" & v(0)) & ",""namespace_id"":" & JsonLite_Quote("" & v(1)) & _ ",""source"":" & NodeRef("" & v(2), "" & v(3)) & ",""target"":" & NodeRef("" & v(4), "" & v(5)) & ",""type"":" & JsonLite_Quote("" & v(6)) & _ ",""description"":" & JStr(v(7)) & ",""confidence"":" & JNum(v(8)) & ",""valid_from"":" & JStr(v(9)) & ",""valid_until"":" & JStr(v(10)) & _ ",""inferred"":" & LCase(CStr(CLng(v(11)) = 1)) & ",""state"":" & JsonLite_Quote("" & v(12)) & ",""author"":" & JStr(v(13)) & _ ",""reviewer"":" & JStr(v(14)) & ",""review_notes"":" & JStr(v(15)) & ",""created_at"":" & JStr(v(16)) & ",""reviewed_at"":" & JStr(v(17)) & "}" End Function Private Function NodeRef(kind, id) NodeRef = "{""kind"":" & JsonLite_Quote(kind) & ",""id"":" & JsonLite_Quote(id) & "}" End Function ' A node of a traversal result with a label (entity name, memory title, document title). Private Function NodeJson(kind, id, depth) Dim rs, s s = "{""kind"":" & JsonLite_Quote(kind) & ",""id"":" & JsonLite_Quote(id) & ",""depth"":" & depth Select Case kind Case "entity" Set rs = DAL().Query("SELECT namespace_id, name, type FROM entities WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) If Not rs.EOF Then s = s & ",""namespace_id"":" & JsonLite_Quote("" & rs(0)) & ",""label"":" & JsonLite_Quote("" & rs(1)) & ",""type"":" & JsonLite_Quote("" & rs(2)) End If Case "memory" Set rs = DAL().Query("SELECT m.namespace_id, r.title, m.type, m.lifecycle_status, m.current_revision, r.verification_status FROM memories m " & _ "JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = m.current_revision WHERE m.id = ? AND m.tenant_id = ?", Array(id, Api_TenantId)) If Not rs.EOF Then s = s & ",""namespace_id"":" & JsonLite_Quote("" & rs(0)) & ",""label"":" & JsonLite_Quote("" & rs(1)) & ",""type"":" & JsonLite_Quote("" & rs(2)) & _ ",""status"":" & JsonLite_Quote("" & rs(3)) & ",""revision"":" & CLng(rs(4)) & ",""verification_status"":" & JsonLite_Quote("" & rs(5)) End If Case Else Set rs = DAL().Query("SELECT namespace_id, title, current_revision FROM documents WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) If Not rs.EOF Then s = s & ",""namespace_id"":" & JsonLite_Quote("" & rs(0)) & ",""label"":" & JsonLite_Quote("" & rs(1)) & ",""revision"":" & CLng(rs(2)) & _ ",""content_trust"":""untrusted_reference""" End If End Select rs.Close NodeJson = s & "}" End Function Private Function EntitySelect() EntitySelect = "SELECT id, namespace_id, type, canonical_key, name, aliases, description, properties, created_by, created_at, updated_at FROM entities" End Function Private Function EntityJson(rs) EntityJson = "{""id"":" & JsonLite_Quote("" & rs(0)) & ",""namespace_id"":" & JsonLite_Quote("" & rs(1)) & ",""type"":" & JsonLite_Quote("" & rs(2)) & _ ",""canonical_key"":" & JsonLite_Quote("" & rs(3)) & ",""name"":" & JsonLite_Quote("" & rs(4)) & ",""aliases"":" & JRaw(rs(5), "[]") & _ ",""description"":" & JStr(rs(6)) & ",""properties"":" & JRaw(rs(7), "{}") & ",""created_by"":" & JStr(rs(8)) & _ ",""created_at"":" & JStr(rs(9)) & ",""updated_at"":" & JStr(rs(10)) & "}" End Function Private Function EntityById(id) Dim rs EntityById = "null" Set rs = DAL().Query(EntitySelect() & " WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) If Not rs.EOF Then EntityById = EntityJson(rs) End If rs.Close End Function Private Function IsEntityType(t) Dim re Set re = New RegExp re.Pattern = "^[a-z][a-z0-9_-]{0,39}$" re.IgnoreCase = False IsEntityType = re.Test(t) End Function ' Reads {"kind","id"} from input(name) into kind/id; adds a validation message when it is missing or malformed. Private Sub ReadEndpoint(input, name, ByRef kind, ByRef id) Dim o kind = "" id = "" If Not input.HasRaw(name) Then AddErr name & " is required: an object with kind (entity, memory or document) and id." Exit Sub End If If Left(input.Raw(name), 1) <> "{" Then AddErr name & " must be an object with kind and id." Exit Sub End If Set o = JsonLite_Parse(input.Raw(name)) If o Is Nothing Then AddErr name & " must be an object with kind and id." Exit Sub End If If o.Exists("kind") Then kind = LCase("" & o.Item("kind")) End If If o.Exists("id") Then id = "" & o.Item("id") End If If Not Graph_IsKind(kind) Then AddErr name & ".kind must be entity, memory or document." kind = "" id = "" ElseIf Not Api_IsId(id) Then AddErr name & ".id must be a valid id." kind = "" id = "" End If End Sub Private Function OptInt(input, name, dflt, lo, hi) Dim v OptInt = dflt If Not input.Exists(name) Then Exit Function End If v = input.Item(name) If IsNull(v) Then Exit Function End If If VarType(v) <> vbDouble Then AddErr name & " must be a whole number from " & lo & " to " & hi & "." Exit Function End If If v <> Int(v) Or v < lo Or v > hi Then AddErr name & " must be a whole number from " & lo & " to " & hi & "." Exit Function End If OptInt = CLng(v) End Function Private Function OptTimestamp(input, name) Dim v, re OptTimestamp = Null v = OptString(input, name, 19) If IsNull(v) Then Exit Function End If Set re = New RegExp re.Pattern = "^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$" If Not re.Test(v) Then AddErr name & " must be a UTC time like 2027-01-31 18:00:00." Exit Function End If OptTimestamp = v End Function Private Function AliasesJson(input) Dim arr, i, out, t AliasesJson = Null If Not input.HasRaw("aliases") Then If input.Exists("aliases") Then If Not IsNull(input.Item("aliases")) Then AddErr "aliases must be an array of strings." End If End If Exit Function End If arr = JsonLite_ParseStringArray(input.Raw("aliases")) If IsNull(arr) Then AddErr "aliases must be an array of strings." Exit Function End If If UBound(arr) > 31 Then AddErr "aliases may contain at most 32 entries." Exit Function End If out = "" For i = 0 To UBound(arr) t = Trim(arr(i)) If Len(t) = 0 Or Len(t) > 200 Then AddErr "each alias must be 1 to 200 characters." Exit Function End If If i > 0 Then out = out & "," End If out = out & JsonLite_Quote(t) Next AliasesJson = "[" & out & "]" End Function Private Function JStr(v) If IsNull(v) Then JStr = "null" ElseIf IsEmpty(v) Then JStr = "null" Else JStr = JsonLite_Quote("" & v) End If End Function Private Function JNum(v) If IsNull(v) Then JNum = "null" ElseIf Len("" & v) = 0 Then JNum = "null" Else JNum = JsonLite_Num(v) End If End Function Private Function JRaw(v, dflt) If IsNull(v) Then JRaw = dflt ElseIf Len("" & v) = 0 Then JRaw = dflt Else JRaw = "" & v End If End Function Private Sub AddErr(msg) If Len(m_errs) > 0 Then m_errs = m_errs & Chr(30) End If m_errs = m_errs & msg End Sub Private Function ReqString(input, name, maxLen) Dim v ReqString = "" If Not input.Exists(name) Then AddErr name & " is required." Exit Function End If v = input.Item(name) If IsNull(v) Then AddErr name & " is required." Exit Function End If If VarType(v) <> vbString Then AddErr name & " must be a string." Exit Function End If v = Trim(v) If Len(v) = 0 Then AddErr name & " must not be empty." Exit Function End If If Len(v) > maxLen Then AddErr name & " must be at most " & maxLen & " characters." Exit Function End If ReqString = v End Function Private Function OptString(input, name, maxLen) Dim v OptString = Null If Not input.Exists(name) Then Exit Function End If v = input.Item(name) If IsNull(v) Then Exit Function End If If VarType(v) <> vbString Then AddErr name & " must be a string." Exit Function End If If Len(v) > maxLen Then AddErr name & " must be at most " & maxLen & " characters." Exit Function End If OptString = v End Function Private Function OptUnit(input, name) Dim v OptUnit = Null If Not input.Exists(name) Then Exit Function End If v = input.Item(name) If IsNull(v) Then Exit Function End If If VarType(v) <> vbDouble Then AddErr name & " must be a number between 0 and 1." Exit Function End If If v < 0 Or v > 1 Then AddErr name & " must be between 0 and 1." Exit Function End If OptUnit = v End Function ' Optional JSON object stored as raw text (max 16 KB), or Null Private Function ObjectJson(input, name) Dim raw ObjectJson = Null If Not input.HasRaw(name) Then If input.Exists(name) Then If Not IsNull(input.Item(name)) Then AddErr name & " must be a JSON object." End If End If Exit Function End If raw = input.Raw(name) If Left(raw, 1) <> "{" Then AddErr name & " must be a JSON object." Exit Function End If If Len(raw) > 16384 Then AddErr name & " must be at most 16 KB." Exit Function End If ObjectJson = raw End Function ' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls and shared call sites) Public Sub Invoke(actionName, args) Select Case LCase(actionName) Case "createentity" : CreateEntity Case "entities" : Entities Case "entity" : Entity args(0) Case "updateentity" : UpdateEntity args(0) Case "deleteentity" : DeleteEntity args(0) Case "relate" : Relate Case "relationships" : Relationships Case "relationship" : Relationship args(0) Case "review" : Review args(0) Case "deleterelationship" : DeleteRelationship args(0) Case "traverse" : Traverse Case Else Err.Raise 438, "ApiGraphController_Class", "Action '" & actionName & "' not found" End Select End Sub End Class Dim ApiGraphController_Class__Singleton Function ApiGraphController() If IsEmpty(ApiGraphController_Class__Singleton) Then Set ApiGraphController_Class__Singleton = New ApiGraphController_Class End If Set ApiGraphController = ApiGraphController_Class__Singleton End Function ' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller) Sub ApiGraphController_Invoke(actionName, args) ApiGraphController().Invoke actionName, args End Sub %>