選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

1276 行
51KB

  1. <%
  2. ' ApiGraphController: entities, typed relationships and bounded traversal (spec FR-023, section 8.1, section 14,
  3. ' ADR-014). Stateless JSON API, no layout. Helpers: core/lib.Graph.asp, core/lib.Learning.asp (evidence).
  4. '
  5. ' POST /api/v1/entities CreateEntity {"namespace_id","type","name","canonical_key","aliases":[],"description","properties":{}}
  6. ' GET /api/v1/entities Entities ?namespace_id= &type= &q= &limit=
  7. ' GET /api/v1/entities/:id Entity
  8. ' PATCH /api/v1/entities/:id UpdateEntity {"name","aliases","description","properties"} (canonical key and type are fixed)
  9. ' DELETE /api/v1/entities/:id DeleteEntity also deletes every relationship touching it
  10. ' POST /api/v1/relate Relate {"namespace_id","source":{"kind","id"},"target":{"kind","id"},"type",
  11. ' "description","confidence","valid_from","valid_until","inferred",
  12. ' "evidence":[{"kind","id","role","excerpt"}]} -> proposed
  13. ' GET /api/v1/relationships Relationships ?namespace_id= &state= &type= &node_kind= &node_id= &limit=
  14. ' GET /api/v1/relationships/:id Relationship with its evidence
  15. ' POST /api/v1/relationships/:id/review Review {"decision":"accept|reject","notes"}
  16. ' DELETE /api/v1/relationships/:id DeleteRelationship
  17. ' POST /api/v1/graph/traverse Traverse {"start":{"kind","id"},"direction":"out|in|both","max_depth":2,
  18. ' "max_nodes":50,"types":[],"include_proposed":false}
  19. '
  20. ' Kinds of endpoints: entity, memory, document. Relationship types are upper-case words (IS_A, PART_OF, DEPENDS_ON,
  21. ' IMPLEMENTS, CALLS, SOLVES, CONTRADICTS, SUPERSEDES, VERIFIED_BY, RELATES_TO, or another of the same form).
  22. ' Permissions on the namespace: write (CreateEntity, UpdateEntity, Relate; Relate also needs read on both endpoints),
  23. ' read (lists, fetches, Traverse), verify (Review; the author needs admin), delete (DeleteEntity, DeleteRelationship).
  24. ' An edge is visible only when the edge's namespace and both endpoints are readable; otherwise it does not exist for
  25. ' the caller (404, or simply left out). Traversal follows accepted edges that are valid now, skips retired memories
  26. ' and is bounded by depth, node and edge limits.
  27. Class ApiGraphController_Class
  28. Private m_errs
  29. Public Property Get useLayout()
  30. useLayout = False
  31. End Property
  32. Public Property Let useLayout(v)
  33. End Property
  34. Public Property Get Title()
  35. Title = "Graph API"
  36. End Property
  37. '---------------------------------------------------------------
  38. ' POST /api/v1/entities
  39. '---------------------------------------------------------------
  40. Public Sub CreateEntity()
  41. Dim body, input, nsId, eType, name, cKey, aliases, descr, props, rs, existing, entId, ts, k
  42. If Not Api_Authenticate() Then Exit Sub
  43. body = Api_ReadBody()
  44. If IsEmpty(body) Then Exit Sub
  45. Set input = JsonLite_Parse(body)
  46. m_errs = ""
  47. nsId = ReqString(input, "namespace_id", 64)
  48. eType = LCase("" & ReqString(input, "type", 40))
  49. name = ReqString(input, "name", 200)
  50. cKey = OptString(input, "canonical_key", 200)
  51. aliases = AliasesJson(input)
  52. descr = OptString(input, "description", 2000)
  53. props = ObjectJson(input, "properties")
  54. If Len(eType) > 0 Then
  55. If Not IsEntityType(eType) Then
  56. AddErr "type must be 1 to 40 characters: lower-case letters, digits, '_' or '-', starting with a letter."
  57. End If
  58. End If
  59. If IsNull(cKey) Then
  60. cKey = Graph_CanonicalKey(name)
  61. Else
  62. cKey = Graph_CanonicalKey(cKey)
  63. If Len(cKey) = 0 Then
  64. AddErr "canonical_key must not be empty."
  65. End If
  66. End If
  67. If Len(m_errs) > 0 Then
  68. Api_Invalid Split(m_errs, Chr(30))
  69. Exit Sub
  70. End If
  71. If Not Api_CanAccessNamespace(nsId, "write") Then
  72. Api_Audit "entity.create", "namespace", nsId, "denied"
  73. Api_Error 404, "namespace_not_found", "Namespace not found."
  74. Exit Sub
  75. End If
  76. Set rs = DAL().Query("SELECT id FROM entities WHERE namespace_id = ? AND type = ? AND canonical_key = ?", Array(nsId, eType, cKey))
  77. existing = ""
  78. If Not rs.EOF Then
  79. existing = "" & rs(0)
  80. End If
  81. rs.Close
  82. If Len(existing) > 0 Then
  83. Api_Send 409, "{""error"":{""code"":""entity_exists"",""message"":""An entity with this type and canonical key already exists in the namespace."",""existing_id"":" & _
  84. JsonLite_Quote(existing) & ",""request_id"":" & JsonLite_Quote(Api_RequestId()) & "}}"
  85. Exit Sub
  86. End If
  87. entId = Api_NewId()
  88. ts = Api_Now()
  89. On Error Resume Next
  90. DAL().BeginTransaction
  91. DAL().Execute "INSERT INTO entities (id, tenant_id, namespace_id, type, canonical_key, name, created_by, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, '" & ts & "')", _
  92. Array(entId, Api_TenantId, nsId, eType, cKey, name, Api_PrincipalId, ts)
  93. DAL().Execute "UPDATE entities SET aliases = ?, description = ?, properties = ? WHERE id = ?", Array(aliases, descr, props, entId)
  94. If Err.Number <> 0 Then
  95. k = Err.Number : Api_NoteDbError
  96. DAL().RollbackTransaction
  97. Api_DbFailed k, ""
  98. Exit Sub
  99. End If
  100. DAL().CommitTransaction
  101. If Err.Number <> 0 Then
  102. k = Err.Number : Api_NoteDbError
  103. Api_DbFailed k, ""
  104. Exit Sub
  105. End If
  106. On Error GoTo 0
  107. Api_Audit "entity.create", "entity", entId, "ok"
  108. Response.AddHeader "Location", "/api/v1/entities/" & entId
  109. Api_Send 201, "{""data"":" & EntityById(entId) & "}"
  110. End Sub
  111. '---------------------------------------------------------------
  112. ' GET /api/v1/entities
  113. '---------------------------------------------------------------
  114. Public Sub Entities()
  115. Dim allowed, nsFilter, eType, q, limit, sql, params, rs, out, n, pat
  116. If Not Api_Authenticate() Then Exit Sub
  117. nsFilter = Trim("" & Request.QueryString("namespace_id"))
  118. eType = LCase(Trim("" & Request.QueryString("type")))
  119. q = Trim("" & Request.QueryString("q"))
  120. limit = Api_ToInt(Request.QueryString("limit"), 50, 1, 200)
  121. If Len(nsFilter) > 0 Then
  122. If Not Api_IsId(nsFilter) Then
  123. Api_Invalid Array("namespace_id must be a valid id.")
  124. Exit Sub
  125. End If
  126. End If
  127. If Len(eType) > 0 Then
  128. If Not IsEntityType(eType) Then
  129. Api_Invalid Array("type is not a valid entity type.")
  130. Exit Sub
  131. End If
  132. End If
  133. If Len(q) > 200 Then
  134. Api_Invalid Array("q must be at most 200 characters.")
  135. Exit Sub
  136. End If
  137. allowed = Api_AllowedNamespaceIds("read")
  138. out = ""
  139. n = 0
  140. If Len(allowed) > 0 Then
  141. sql = EntitySelect() & " WHERE tenant_id = ? AND namespace_id IN (" & allowed & ")"
  142. If Len(nsFilter) > 0 Then
  143. sql = sql & " AND namespace_id = '" & nsFilter & "'"
  144. End If
  145. If Len(eType) > 0 Then
  146. sql = sql & " AND type = '" & eType & "'"
  147. End If
  148. If Len(q) > 0 Then
  149. ' name, canonical key or an alias contains q ('!' escapes LIKE wildcards)
  150. pat = "%" & Replace(Replace(Replace(LCase(q), "!", "!!"), "%", "!%"), "_", "!_") & "%"
  151. sql = sql & " AND (LOWER(name) LIKE ? ESCAPE '!' OR canonical_key LIKE ? ESCAPE '!' OR LOWER(COALESCE(aliases, '')) LIKE ? ESCAPE '!')"
  152. params = Array(Api_TenantId, pat, pat, pat)
  153. Else
  154. params = Api_TenantId
  155. End If
  156. Set rs = DAL().Query(sql & " ORDER BY name, id LIMIT " & limit, params)
  157. Do While Not rs.EOF
  158. If n > 0 Then
  159. out = out & ","
  160. End If
  161. out = out & EntityJson(rs)
  162. n = n + 1
  163. rs.MoveNext
  164. Loop
  165. rs.Close
  166. End If
  167. Api_Send 200, "{""data"":[" & out & "]}"
  168. End Sub
  169. '---------------------------------------------------------------
  170. ' GET /api/v1/entities/:id
  171. '---------------------------------------------------------------
  172. Public Sub Entity(id)
  173. Dim nsId
  174. If Not Api_Authenticate() Then Exit Sub
  175. nsId = Graph_NodeNamespace("entity", id)
  176. If Len(nsId) = 0 Then
  177. Api_NotFound
  178. Exit Sub
  179. End If
  180. If Not Api_CanAccessNamespace(nsId, "read") Then
  181. Api_NotFound
  182. Exit Sub
  183. End If
  184. Api_Send 200, "{""data"":" & EntityById(id) & "}"
  185. End Sub
  186. '---------------------------------------------------------------
  187. ' PATCH /api/v1/entities/:id
  188. '---------------------------------------------------------------
  189. Public Sub UpdateEntity(id)
  190. Dim body, input, nsId, sets, vals, name, aliases, descr, props, k, i, params
  191. If Not Api_Authenticate() Then Exit Sub
  192. nsId = Graph_NodeNamespace("entity", id)
  193. If Len(nsId) = 0 Then
  194. Api_NotFound
  195. Exit Sub
  196. End If
  197. If Not Api_CanAccessNamespace(nsId, "write") Then
  198. Api_Audit "entity.update", "entity", id, "denied"
  199. Api_NotFound
  200. Exit Sub
  201. End If
  202. body = Api_ReadBody()
  203. If IsEmpty(body) Then Exit Sub
  204. Set input = JsonLite_Parse(body)
  205. m_errs = ""
  206. sets = ""
  207. vals = ""
  208. If input.Exists("canonical_key") Or input.Exists("type") Or input.Exists("namespace_id") Then
  209. AddErr "type, canonical_key and namespace_id cannot be changed; create a new entity instead."
  210. End If
  211. If input.Exists("name") Then
  212. name = ReqString(input, "name", 200)
  213. sets = sets & "name = ?, "
  214. vals = vals & Chr(30) & "name"
  215. End If
  216. If input.Exists("aliases") Then
  217. aliases = AliasesJson(input)
  218. sets = sets & "aliases = ?, "
  219. vals = vals & Chr(30) & "aliases"
  220. End If
  221. If input.Exists("description") Then
  222. descr = OptString(input, "description", 2000)
  223. sets = sets & "description = ?, "
  224. vals = vals & Chr(30) & "description"
  225. End If
  226. If input.Exists("properties") Then
  227. props = ObjectJson(input, "properties")
  228. sets = sets & "properties = ?, "
  229. vals = vals & Chr(30) & "properties"
  230. End If
  231. If Len(m_errs) = 0 Then
  232. If Len(sets) = 0 Then
  233. AddErr "Nothing to change: give name, aliases, description or properties."
  234. End If
  235. End If
  236. If Len(m_errs) > 0 Then
  237. Api_Invalid Split(m_errs, Chr(30))
  238. Exit Sub
  239. End If
  240. vals = Split(Mid(vals, 2), Chr(30))
  241. ReDim params(UBound(vals) + 2)
  242. For i = 0 To UBound(vals)
  243. Select Case vals(i)
  244. Case "name"
  245. params(i) = name
  246. Case "aliases"
  247. params(i) = aliases
  248. Case "description"
  249. params(i) = descr
  250. Case "properties"
  251. params(i) = props
  252. End Select
  253. Next
  254. params(UBound(vals) + 1) = Api_Now()
  255. params(UBound(vals) + 2) = id
  256. On Error Resume Next
  257. DAL().Execute "UPDATE entities SET " & sets & "updated_at = ? WHERE id = ?", params
  258. If Err.Number <> 0 Then
  259. k = Err.Number : Api_NoteDbError
  260. Api_DbFailed k, ""
  261. Exit Sub
  262. End If
  263. On Error GoTo 0
  264. Api_Audit "entity.update", "entity", id, "ok"
  265. Api_Send 200, "{""data"":" & EntityById(id) & "}"
  266. End Sub
  267. '---------------------------------------------------------------
  268. ' DELETE /api/v1/entities/:id
  269. '---------------------------------------------------------------
  270. Public Sub DeleteEntity(id)
  271. Dim nsId, k
  272. If Not Api_Authenticate() Then Exit Sub
  273. nsId = Graph_NodeNamespace("entity", id)
  274. If Len(nsId) = 0 Then
  275. Api_NotFound
  276. Exit Sub
  277. End If
  278. If Not Api_CanAccessNamespace(nsId, "delete") Then
  279. Api_Audit "entity.delete", "entity", id, "denied"
  280. Api_NotFound
  281. Exit Sub
  282. End If
  283. On Error Resume Next
  284. DAL().BeginTransaction
  285. Graph_ForgetNode "entity", id
  286. DAL().Execute "DELETE FROM entities WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)
  287. If Err.Number <> 0 Then
  288. k = Err.Number : Api_NoteDbError
  289. DAL().RollbackTransaction
  290. Api_DbFailed k, ""
  291. Exit Sub
  292. End If
  293. DAL().CommitTransaction
  294. If Err.Number <> 0 Then
  295. k = Err.Number : Api_NoteDbError
  296. Api_DbFailed k, ""
  297. Exit Sub
  298. End If
  299. On Error GoTo 0
  300. Api_Audit "entity.delete", "entity", id, "ok"
  301. Api_Send 200, "{""deleted"":true,""id"":" & JsonLite_Quote(id) & "}"
  302. End Sub
  303. '---------------------------------------------------------------
  304. ' POST /api/v1/relate
  305. '---------------------------------------------------------------
  306. Public Sub Relate()
  307. Dim body, input, idemKey, reqHash, nsId, sKind, sId, tKind, tId, rType, descr, confidence, vFrom, vUntil, inferred
  308. Dim ev, msg, rs, relId, ts, resp, k, ns2
  309. If Not Api_Authenticate() Then Exit Sub
  310. body = Api_ReadBody()
  311. If IsEmpty(body) Then Exit Sub
  312. Set input = JsonLite_Parse(body)
  313. idemKey = Api_Header("Idempotency-Key")
  314. If Len(idemKey) > 200 Then
  315. Api_Error 400, "invalid_idempotency_key", "Idempotency-Key must be at most 200 characters."
  316. Exit Sub
  317. End If
  318. reqHash = Api_Sha256("relate|" & body)
  319. If Not Api_IdempotencyGate(idemKey, reqHash) Then Exit Sub
  320. m_errs = ""
  321. nsId = ReqString(input, "namespace_id", 64)
  322. ReadEndpoint input, "source", sKind, sId
  323. ReadEndpoint input, "target", tKind, tId
  324. rType = UCase("" & ReqString(input, "type", 40))
  325. descr = OptString(input, "description", 2000)
  326. confidence = OptUnit(input, "confidence")
  327. vFrom = OptTimestamp(input, "valid_from")
  328. vUntil = OptTimestamp(input, "valid_until")
  329. inferred = 0
  330. If input.Exists("inferred") Then
  331. If VarType(input.Item("inferred")) = vbBoolean Then
  332. If input.Item("inferred") Then
  333. inferred = 1
  334. End If
  335. ElseIf Not IsNull(input.Item("inferred")) Then
  336. AddErr "inferred must be true or false."
  337. End If
  338. End If
  339. If Len(rType) > 0 Then
  340. If Not Graph_IsType(rType) Then
  341. AddErr "type must be 2 to 40 characters: letters, digits or '_', starting with a letter (for example DEPENDS_ON)."
  342. End If
  343. End If
  344. If Not IsNull(vFrom) Then
  345. If Not IsNull(vUntil) Then
  346. If vUntil <= vFrom Then
  347. AddErr "valid_until must be later than valid_from."
  348. End If
  349. End If
  350. End If
  351. If Len(sId) > 0 Then
  352. If sKind = tKind And sId = tId Then
  353. AddErr "source and target must be different."
  354. End If
  355. End If
  356. If Len(m_errs) > 0 Then
  357. Api_Invalid Split(m_errs, Chr(30))
  358. Exit Sub
  359. End If
  360. If Not Api_CanAccessNamespace(nsId, "write") Then
  361. Api_Audit "relationship.propose", "namespace", nsId, "denied"
  362. Api_Error 404, "namespace_not_found", "Namespace not found."
  363. Exit Sub
  364. End If
  365. ' Both endpoints must exist in this tenant and be readable; an unreadable one is reported like a missing one.
  366. ns2 = Graph_NodeNamespace(sKind, sId)
  367. If Len(ns2) > 0 Then
  368. If Not Api_CanAccessNamespace(ns2, "read") Then
  369. ns2 = ""
  370. End If
  371. End If
  372. If Len(ns2) = 0 Then
  373. Api_Invalid Array("source was not found.")
  374. Exit Sub
  375. End If
  376. ns2 = Graph_NodeNamespace(tKind, tId)
  377. If Len(ns2) > 0 Then
  378. If Not Api_CanAccessNamespace(ns2, "read") Then
  379. ns2 = ""
  380. End If
  381. End If
  382. If Len(ns2) = 0 Then
  383. Api_Invalid Array("target was not found.")
  384. Exit Sub
  385. End If
  386. Set ev = New Evidence_Class
  387. msg = ev.Load(input, "evidence")
  388. If Len(msg) > 0 Then
  389. Api_Invalid Array(msg)
  390. Exit Sub
  391. End If
  392. If ev.Count = 0 Then
  393. Api_Invalid Array("evidence must contain at least one item: graph assertions need evidence.")
  394. Exit Sub
  395. End If
  396. 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 = ? " & _
  397. "AND state IN ('proposed','accepted')", Array(nsId, sKind, sId, tKind, tId, rType))
  398. If Not rs.EOF Then
  399. resp = "{""error"":{""code"":""relationship_exists"",""message"":""This relationship is already " & rs(1) & " in the namespace."",""existing_id"":" & _
  400. JsonLite_Quote("" & rs(0)) & ",""request_id"":" & JsonLite_Quote(Api_RequestId()) & "}}"
  401. rs.Close
  402. Api_Send 409, resp
  403. Exit Sub
  404. End If
  405. rs.Close
  406. relId = Api_NewId()
  407. ts = Api_Now()
  408. resp = "{""id"":" & JsonLite_Quote(relId) & ",""state"":""proposed"",""namespace_id"":" & JsonLite_Quote(nsId) & ",""type"":" & JsonLite_Quote(rType) & _
  409. ",""source"":" & NodeRef(sKind, sId) & ",""target"":" & NodeRef(tKind, tId) & ",""evidence_count"":" & ev.Count & "}"
  410. On Error Resume Next
  411. DAL().BeginTransaction
  412. ' NOT NULL author and time are server values (a principal id from the database and Api_Now), inlined because
  413. ' G3DB takes at most 8 parameters
  414. DAL().Execute "INSERT INTO relationships (id, tenant_id, namespace_id, source_kind, source_id, target_kind, target_id, type, author_principal_id, created_at) " & _
  415. "VALUES (?, ?, ?, ?, ?, ?, ?, ?, '" & Api_PrincipalId & "', '" & ts & "')", Array(relId, Api_TenantId, nsId, sKind, sId, tKind, tId, rType)
  416. DAL().Execute "UPDATE relationships SET description = ?, confidence = ?, valid_from = ?, valid_until = ?, inferred = " & inferred & " WHERE id = ?", _
  417. Array(descr, confidence, vFrom, vUntil, relId)
  418. ev.Save "relationship", relId, Null
  419. Api_IdempotencyStore idemKey, reqHash, 201, resp
  420. If Err.Number <> 0 Then
  421. k = Err.Number : Api_NoteDbError
  422. DAL().RollbackTransaction
  423. Api_DbFailed k, ""
  424. Exit Sub
  425. End If
  426. DAL().CommitTransaction
  427. If Err.Number <> 0 Then
  428. k = Err.Number : Api_NoteDbError
  429. Api_DbFailed k, ""
  430. Exit Sub
  431. End If
  432. On Error GoTo 0
  433. Api_Audit "relationship.propose", "relationship", relId, "ok"
  434. Response.AddHeader "Location", "/api/v1/relationships/" & relId
  435. Api_Send 201, resp
  436. End Sub
  437. '---------------------------------------------------------------
  438. ' GET /api/v1/relationships
  439. '---------------------------------------------------------------
  440. Public Sub Relationships()
  441. Dim allowed, nsFilter, state, rType, nKind, nId, limit, sql, rs, out, n
  442. If Not Api_Authenticate() Then Exit Sub
  443. nsFilter = Trim("" & Request.QueryString("namespace_id"))
  444. state = LCase(Trim("" & Request.QueryString("state")))
  445. rType = UCase(Trim("" & Request.QueryString("type")))
  446. nKind = LCase(Trim("" & Request.QueryString("node_kind")))
  447. nId = Trim("" & Request.QueryString("node_id"))
  448. limit = Api_ToInt(Request.QueryString("limit"), 50, 1, 200)
  449. m_errs = ""
  450. If Len(nsFilter) > 0 Then
  451. If Not Api_IsId(nsFilter) Then
  452. AddErr "namespace_id must be a valid id."
  453. End If
  454. End If
  455. If Len(state) > 0 Then
  456. If state <> "proposed" And state <> "accepted" And state <> "rejected" Then
  457. AddErr "state must be proposed, accepted or rejected."
  458. End If
  459. End If
  460. If Len(rType) > 0 Then
  461. If Not Graph_IsType(rType) Then
  462. AddErr "type is not a valid relationship type."
  463. End If
  464. End If
  465. If Len(nKind) > 0 Or Len(nId) > 0 Then
  466. If Not Graph_IsKind(nKind) Then
  467. AddErr "node_kind must be entity, memory or document (with node_id)."
  468. ElseIf Not Api_IsId(nId) Then
  469. AddErr "node_id must be a valid id (with node_kind)."
  470. End If
  471. End If
  472. If Len(m_errs) > 0 Then
  473. Api_Invalid Split(m_errs, Chr(30))
  474. Exit Sub
  475. End If
  476. allowed = Api_AllowedNamespaceIds("read")
  477. out = ""
  478. n = 0
  479. If Len(allowed) > 0 Then
  480. sql = RelSelect() & " WHERE r.tenant_id = ? AND r.namespace_id IN (" & allowed & ") AND " & _
  481. Graph_NodeVisibleSql("source", allowed, False) & " AND " & Graph_NodeVisibleSql("target", allowed, False)
  482. If Len(nsFilter) > 0 Then
  483. sql = sql & " AND r.namespace_id = '" & nsFilter & "'"
  484. End If
  485. If Len(state) > 0 Then
  486. sql = sql & " AND r.state = '" & state & "'"
  487. End If
  488. If Len(rType) > 0 Then
  489. sql = sql & " AND r.type = '" & rType & "'"
  490. End If
  491. If Len(nKind) > 0 Then
  492. sql = sql & " AND ((r.source_kind = '" & nKind & "' AND r.source_id = '" & nId & "') OR (r.target_kind = '" & nKind & "' AND r.target_id = '" & nId & "'))"
  493. End If
  494. Set rs = DAL().Query(sql & " ORDER BY r.created_at DESC, r.id LIMIT " & limit, Api_TenantId)
  495. Do While Not rs.EOF
  496. If n > 0 Then
  497. out = out & ","
  498. End If
  499. out = out & RelJson(rs)
  500. n = n + 1
  501. rs.MoveNext
  502. Loop
  503. rs.Close
  504. End If
  505. Api_Send 200, "{""data"":[" & out & "]}"
  506. End Sub
  507. '---------------------------------------------------------------
  508. ' GET /api/v1/relationships/:id
  509. '---------------------------------------------------------------
  510. Public Sub Relationship(id)
  511. Dim json
  512. If Not Api_Authenticate() Then Exit Sub
  513. json = VisibleRelJson(id, "read")
  514. If Len(json) = 0 Then
  515. Api_NotFound
  516. Exit Sub
  517. End If
  518. json = Left(json, Len(json) - 1) & ",""evidence"":" & Evidence_Json("relationship", id, Null) & "}"
  519. Api_Send 200, "{""data"":" & json & "}"
  520. End Sub
  521. '---------------------------------------------------------------
  522. ' POST /api/v1/relationships/:id/review
  523. '---------------------------------------------------------------
  524. Public Sub Review(id)
  525. Dim body, input, rs, nsId, state, author, decision, notes, k, newState
  526. If Not Api_Authenticate() Then Exit Sub
  527. If Len(VisibleRelJson(id, "verify")) = 0 Then
  528. Api_Audit "relationship.review", "relationship", id, "denied"
  529. Api_NotFound
  530. Exit Sub
  531. End If
  532. body = Api_ReadBody()
  533. If IsEmpty(body) Then Exit Sub
  534. Set input = JsonLite_Parse(body)
  535. Set rs = DAL().Query("SELECT namespace_id, state, author_principal_id FROM relationships WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  536. If rs.EOF Then
  537. rs.Close
  538. Api_NotFound
  539. Exit Sub
  540. End If
  541. nsId = "" & rs(0)
  542. state = "" & rs(1)
  543. author = "" & rs(2)
  544. rs.Close
  545. m_errs = ""
  546. decision = LCase("" & ReqString(input, "decision", 20))
  547. notes = OptString(input, "notes", 2000)
  548. If Len(m_errs) = 0 Then
  549. If decision <> "accept" And decision <> "reject" Then
  550. AddErr "decision must be accept or reject."
  551. End If
  552. End If
  553. If Len(m_errs) > 0 Then
  554. Api_Invalid Split(m_errs, Chr(30))
  555. Exit Sub
  556. End If
  557. If state <> "proposed" Then
  558. Api_Error 409, "relationship_already_reviewed", "The relationship was already " & state & "."
  559. Exit Sub
  560. End If
  561. If author = Api_PrincipalId Then
  562. If Not Api_CanAccessNamespace(nsId, "admin") Then
  563. Api_Audit "relationship.review", "relationship", id, "self_review_denied"
  564. Api_Error 403, "self_review_not_allowed", "A relationship cannot be reviewed by its author without admin permission on the namespace."
  565. Exit Sub
  566. End If
  567. End If
  568. newState = "rejected"
  569. If decision = "accept" Then
  570. newState = "accepted"
  571. End If
  572. On Error Resume Next
  573. DAL().Execute "UPDATE relationships SET state = ?, reviewer_principal_id = ?, review_notes = ?, reviewed_at = ? WHERE id = ? AND state = 'proposed'", _
  574. Array(newState, Api_PrincipalId, notes, Api_Now(), id)
  575. If Err.Number <> 0 Then
  576. k = Err.Number : Api_NoteDbError
  577. Api_DbFailed k, ""
  578. Exit Sub
  579. End If
  580. On Error GoTo 0
  581. Api_Audit "relationship.review", "relationship", id, newState
  582. Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""state"":" & JsonLite_Quote(newState) & "}"
  583. End Sub
  584. '---------------------------------------------------------------
  585. ' DELETE /api/v1/relationships/:id
  586. '---------------------------------------------------------------
  587. Public Sub DeleteRelationship(id)
  588. Dim k
  589. If Not Api_Authenticate() Then Exit Sub
  590. If Len(VisibleRelJson(id, "delete")) = 0 Then
  591. Api_Audit "relationship.delete", "relationship", id, "denied"
  592. Api_NotFound
  593. Exit Sub
  594. End If
  595. On Error Resume Next
  596. DAL().BeginTransaction
  597. DAL().Execute "DELETE FROM evidence_links WHERE owner_kind = 'relationship' AND owner_id = ?", id
  598. DAL().Execute "DELETE FROM relationships WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)
  599. If Err.Number <> 0 Then
  600. k = Err.Number : Api_NoteDbError
  601. DAL().RollbackTransaction
  602. Api_DbFailed k, ""
  603. Exit Sub
  604. End If
  605. DAL().CommitTransaction
  606. If Err.Number <> 0 Then
  607. k = Err.Number : Api_NoteDbError
  608. Api_DbFailed k, ""
  609. Exit Sub
  610. End If
  611. On Error GoTo 0
  612. Api_Audit "relationship.delete", "relationship", id, "ok"
  613. Api_Send 200, "{""deleted"":true,""id"":" & JsonLite_Quote(id) & "}"
  614. End Sub
  615. '---------------------------------------------------------------
  616. ' POST /api/v1/graph/traverse
  617. '---------------------------------------------------------------
  618. Public Sub Traverse()
  619. Dim body, input, sKind, sId, direction, maxDepth, maxNodes, types, includeProposed, startNs, allowed
  620. Dim baseSql, typeSql, arr, i, nowTs, visited, seenEdges, frontier, nextFrontier, depth, frontierSet
  621. Dim cond, rs, rows, j, eid, srcKey, tgtKey, oKind, oId, oKey, nodes, edges, nodeCount, edgeCount, truncated, stopAll
  622. If Not Api_Authenticate() Then Exit Sub
  623. body = Api_ReadBody()
  624. If IsEmpty(body) Then Exit Sub
  625. Set input = JsonLite_Parse(body)
  626. m_errs = ""
  627. ReadEndpoint input, "start", sKind, sId
  628. direction = "both"
  629. If input.Exists("direction") Then
  630. direction = LCase("" & input.Item("direction"))
  631. If direction <> "out" And direction <> "in" And direction <> "both" Then
  632. AddErr "direction must be out, in or both."
  633. End If
  634. End If
  635. maxDepth = OptInt(input, "max_depth", 2, 1, GRAPH_MAX_DEPTH)
  636. maxNodes = OptInt(input, "max_nodes", 50, 1, GRAPH_MAX_NODES)
  637. includeProposed = False
  638. If input.Exists("include_proposed") Then
  639. If VarType(input.Item("include_proposed")) = vbBoolean Then
  640. includeProposed = input.Item("include_proposed")
  641. ElseIf Not IsNull(input.Item("include_proposed")) Then
  642. AddErr "include_proposed must be true or false."
  643. End If
  644. End If
  645. typeSql = ""
  646. If input.HasRaw("types") Then
  647. arr = JsonLite_ParseStringArray(input.Raw("types"))
  648. If IsNull(arr) Then
  649. AddErr "types must be an array of strings."
  650. ElseIf UBound(arr) > 19 Then
  651. AddErr "types may contain at most 20 entries."
  652. Else
  653. For i = 0 To UBound(arr)
  654. If Not Graph_IsType(UCase(Trim(arr(i)))) Then
  655. AddErr "types[" & i & "] is not a valid relationship type."
  656. Exit For
  657. End If
  658. If Len(typeSql) > 0 Then
  659. typeSql = typeSql & ","
  660. End If
  661. typeSql = typeSql & "'" & UCase(Trim(arr(i))) & "'"
  662. Next
  663. End If
  664. ElseIf input.Exists("types") Then
  665. If Not IsNull(input.Item("types")) Then
  666. AddErr "types must be an array of strings."
  667. End If
  668. End If
  669. If Len(m_errs) > 0 Then
  670. Api_Invalid Split(m_errs, Chr(30))
  671. Exit Sub
  672. End If
  673. startNs = Graph_NodeNamespace(sKind, sId)
  674. If Len(startNs) > 0 Then
  675. If Not Api_CanAccessNamespace(startNs, "read") Then
  676. startNs = ""
  677. End If
  678. End If
  679. If Len(startNs) = 0 Then
  680. Api_NotFound
  681. Exit Sub
  682. End If
  683. allowed = Api_AllowedNamespaceIds("read")
  684. ' Edges the caller may see: readable edge namespace, both endpoints readable (retired memories left out,
  685. ' except the start node itself), accepted (or proposed on request), valid now, of the requested types.
  686. nowTs = Api_Now()
  687. baseSql = RelSelect() & " WHERE r.tenant_id = ? AND r.namespace_id IN (" & allowed & ")"
  688. If includeProposed Then
  689. baseSql = baseSql & " AND r.state IN ('accepted','proposed')"
  690. Else
  691. baseSql = baseSql & " AND r.state = 'accepted'"
  692. End If
  693. baseSql = baseSql & " AND (r.valid_from IS NULL OR r.valid_from <= '" & nowTs & "') AND (r.valid_until IS NULL OR r.valid_until > '" & nowTs & "')"
  694. If Len(typeSql) > 0 Then
  695. baseSql = baseSql & " AND r.type IN (" & typeSql & ")"
  696. End If
  697. baseSql = baseSql & " AND (" & Graph_NodeVisibleSql("source", allowed, True) & " OR (r.source_kind = '" & sKind & "' AND r.source_id = '" & sId & "'))" & _
  698. " AND (" & Graph_NodeVisibleSql("target", allowed, True) & " OR (r.target_kind = '" & sKind & "' AND r.target_id = '" & sId & "'))"
  699. visited = "|" & sKind & ":" & sId & "|"
  700. seenEdges = "|"
  701. frontier = sKind & ":" & sId
  702. nodes = NodeJson(sKind, sId, 0)
  703. edges = ""
  704. nodeCount = 1
  705. edgeCount = 0
  706. truncated = False
  707. stopAll = False
  708. For depth = 1 To maxDepth
  709. If Len(frontier) = 0 Or stopAll Then
  710. Exit For
  711. End If
  712. frontierSet = "|" & Replace(frontier, Chr(30), "|") & "|"
  713. cond = ""
  714. If direction <> "in" Then
  715. cond = FrontierSql("source", frontier)
  716. End If
  717. If direction <> "out" Then
  718. If Len(cond) > 0 Then
  719. cond = cond & " OR "
  720. End If
  721. cond = cond & FrontierSql("target", frontier)
  722. End If
  723. Set rs = DAL().Query(baseSql & " AND (" & cond & ") ORDER BY r.created_at, r.id LIMIT " & (GRAPH_MAX_EDGES + 1), Api_TenantId)
  724. rows = Empty
  725. If Not rs.EOF Then
  726. rows = rs.GetRows()
  727. End If
  728. rs.Close
  729. nextFrontier = ""
  730. If Not IsEmpty(rows) Then
  731. For j = 0 To UBound(rows, 2)
  732. eid = "" & rows(0, j)
  733. If InStr(seenEdges, "|" & eid & "|") = 0 Then
  734. srcKey = rows(2, j) & ":" & rows(3, j)
  735. tgtKey = rows(4, j) & ":" & rows(5, j)
  736. oKey = ""
  737. If direction <> "in" Then
  738. If InStr(frontierSet, "|" & srcKey & "|") > 0 Then
  739. oKind = "" & rows(4, j)
  740. oId = "" & rows(5, j)
  741. oKey = tgtKey
  742. End If
  743. End If
  744. If Len(oKey) = 0 Then
  745. If direction <> "out" Then
  746. If InStr(frontierSet, "|" & tgtKey & "|") > 0 Then
  747. oKind = "" & rows(2, j)
  748. oId = "" & rows(3, j)
  749. oKey = srcKey
  750. End If
  751. End If
  752. End If
  753. If Len(oKey) > 0 Then
  754. If edgeCount >= GRAPH_MAX_EDGES Then
  755. truncated = True
  756. stopAll = True
  757. Exit For
  758. End If
  759. If InStr(visited, "|" & oKey & "|") = 0 Then
  760. If nodeCount >= maxNodes Then
  761. truncated = True
  762. oKey = ""
  763. Else
  764. nodes = nodes & "," & NodeJson(oKind, oId, depth)
  765. nodeCount = nodeCount + 1
  766. visited = visited & oKey & "|"
  767. If Len(nextFrontier) > 0 Then
  768. nextFrontier = nextFrontier & Chr(30)
  769. End If
  770. nextFrontier = nextFrontier & oKey
  771. End If
  772. End If
  773. End If
  774. If Len(oKey) > 0 Then
  775. seenEdges = seenEdges & eid & "|"
  776. If edgeCount > 0 Then
  777. edges = edges & ","
  778. End If
  779. edges = edges & RelJsonRow(rows, j)
  780. edgeCount = edgeCount + 1
  781. End If
  782. End If
  783. Next
  784. End If
  785. frontier = nextFrontier
  786. Next
  787. Api_Send 200, "{""start"":" & NodeRef(sKind, sId) & ",""direction"":" & JsonLite_Quote(direction) & ",""max_depth"":" & maxDepth & _
  788. ",""nodes"":[" & nodes & "],""edges"":[" & edges & "],""truncated"":" & LCase(CStr(truncated)) & "}"
  789. End Sub
  790. '---------------------------------------------------------------
  791. ' Helpers
  792. '---------------------------------------------------------------
  793. ' "(r.<side>_kind = 'k' AND r.<side>_id IN (...)) OR ..." for the frontier keys ("kind:id" joined by Chr(30));
  794. ' kinds and ids come from the database and were validated, so inlining them is safe.
  795. Private Function FrontierSql(side, frontier)
  796. Dim keys, kinds, k, i, ids, out, p
  797. keys = Split(frontier, Chr(30))
  798. kinds = Array("entity", "memory", "document")
  799. out = ""
  800. For k = 0 To 2
  801. ids = ""
  802. For i = 0 To UBound(keys)
  803. p = InStr(keys(i), ":")
  804. If Left(keys(i), p - 1) = kinds(k) Then
  805. If Api_IsId(Mid(keys(i), p + 1)) Then
  806. If Len(ids) > 0 Then
  807. ids = ids & ","
  808. End If
  809. ids = ids & "'" & Mid(keys(i), p + 1) & "'"
  810. End If
  811. End If
  812. Next
  813. If Len(ids) > 0 Then
  814. If Len(out) > 0 Then
  815. out = out & " OR "
  816. End If
  817. out = out & "(r." & side & "_kind = '" & kinds(k) & "' AND r." & side & "_id IN (" & ids & "))"
  818. End If
  819. Next
  820. If Len(out) = 0 Then
  821. out = "1 = 0"
  822. End If
  823. FrontierSql = "(" & out & ")"
  824. End Function
  825. ' The relationship as JSON when the caller holds perm on its namespace and can read both endpoints, else "".
  826. Private Function VisibleRelJson(id, perm)
  827. Dim rs, json, nsId, ok, sKind, sId, tKind, tId
  828. VisibleRelJson = ""
  829. If Not Api_IsId(id) Then
  830. Exit Function
  831. End If
  832. Set rs = DAL().Query(RelSelect() & " WHERE r.id = ? AND r.tenant_id = ?", Array(id, Api_TenantId))
  833. If rs.EOF Then
  834. rs.Close
  835. Exit Function
  836. End If
  837. nsId = "" & rs(1)
  838. json = RelJson(rs)
  839. sKind = "" & rs(2)
  840. sId = "" & rs(3)
  841. tKind = "" & rs(4)
  842. tId = "" & rs(5)
  843. rs.Close
  844. ok = EndpointReadable(sKind, sId)
  845. If ok Then
  846. ok = EndpointReadable(tKind, tId)
  847. End If
  848. If Not ok Then
  849. Exit Function
  850. End If
  851. If Not Api_CanAccessNamespace(nsId, perm) Then
  852. Exit Function
  853. End If
  854. If perm <> "read" Then
  855. ' Write-type permissions do not imply read in grants: the caller must also be able to see the edge.
  856. If Not Api_CanAccessNamespace(nsId, "read") Then
  857. Exit Function
  858. End If
  859. End If
  860. VisibleRelJson = json
  861. End Function
  862. Private Function EndpointReadable(kind, id)
  863. Dim ns
  864. EndpointReadable = False
  865. ns = Graph_NodeNamespace(kind, id)
  866. If Len(ns) > 0 Then
  867. EndpointReadable = Api_CanAccessNamespace(ns, "read")
  868. End If
  869. End Function
  870. Private Function RelSelect()
  871. 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, " & _
  872. "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"
  873. End Function
  874. Private Function RelJson(rs)
  875. Dim v, i
  876. ReDim v(17)
  877. For i = 0 To 17
  878. v(i) = rs(i)
  879. Next
  880. RelJson = RelJsonValues(v)
  881. End Function
  882. Private Function RelJsonRow(rows, j)
  883. Dim v, i
  884. ReDim v(17)
  885. For i = 0 To 17
  886. v(i) = rows(i, j)
  887. Next
  888. RelJsonRow = RelJsonValues(v)
  889. End Function
  890. Private Function RelJsonValues(v)
  891. RelJsonValues = "{""id"":" & JsonLite_Quote("" & v(0)) & ",""namespace_id"":" & JsonLite_Quote("" & v(1)) & _
  892. ",""source"":" & NodeRef("" & v(2), "" & v(3)) & ",""target"":" & NodeRef("" & v(4), "" & v(5)) & ",""type"":" & JsonLite_Quote("" & v(6)) & _
  893. ",""description"":" & JStr(v(7)) & ",""confidence"":" & JNum(v(8)) & ",""valid_from"":" & JStr(v(9)) & ",""valid_until"":" & JStr(v(10)) & _
  894. ",""inferred"":" & LCase(CStr(CLng(v(11)) = 1)) & ",""state"":" & JsonLite_Quote("" & v(12)) & ",""author"":" & JStr(v(13)) & _
  895. ",""reviewer"":" & JStr(v(14)) & ",""review_notes"":" & JStr(v(15)) & ",""created_at"":" & JStr(v(16)) & ",""reviewed_at"":" & JStr(v(17)) & "}"
  896. End Function
  897. Private Function NodeRef(kind, id)
  898. NodeRef = "{""kind"":" & JsonLite_Quote(kind) & ",""id"":" & JsonLite_Quote(id) & "}"
  899. End Function
  900. ' A node of a traversal result with a label (entity name, memory title, document title).
  901. Private Function NodeJson(kind, id, depth)
  902. Dim rs, s
  903. s = "{""kind"":" & JsonLite_Quote(kind) & ",""id"":" & JsonLite_Quote(id) & ",""depth"":" & depth
  904. Select Case kind
  905. Case "entity"
  906. Set rs = DAL().Query("SELECT namespace_id, name, type FROM entities WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  907. If Not rs.EOF Then
  908. s = s & ",""namespace_id"":" & JsonLite_Quote("" & rs(0)) & ",""label"":" & JsonLite_Quote("" & rs(1)) & ",""type"":" & JsonLite_Quote("" & rs(2))
  909. End If
  910. Case "memory"
  911. Set rs = DAL().Query("SELECT m.namespace_id, r.title, m.type, m.lifecycle_status, m.current_revision, r.verification_status FROM memories m " & _
  912. "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))
  913. If Not rs.EOF Then
  914. s = s & ",""namespace_id"":" & JsonLite_Quote("" & rs(0)) & ",""label"":" & JsonLite_Quote("" & rs(1)) & ",""type"":" & JsonLite_Quote("" & rs(2)) & _
  915. ",""status"":" & JsonLite_Quote("" & rs(3)) & ",""revision"":" & CLng(rs(4)) & ",""verification_status"":" & JsonLite_Quote("" & rs(5))
  916. End If
  917. Case Else
  918. Set rs = DAL().Query("SELECT namespace_id, title, current_revision FROM documents WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  919. If Not rs.EOF Then
  920. s = s & ",""namespace_id"":" & JsonLite_Quote("" & rs(0)) & ",""label"":" & JsonLite_Quote("" & rs(1)) & ",""revision"":" & CLng(rs(2)) & _
  921. ",""content_trust"":""untrusted_reference"""
  922. End If
  923. End Select
  924. rs.Close
  925. NodeJson = s & "}"
  926. End Function
  927. Private Function EntitySelect()
  928. EntitySelect = "SELECT id, namespace_id, type, canonical_key, name, aliases, description, properties, created_by, created_at, updated_at FROM entities"
  929. End Function
  930. Private Function EntityJson(rs)
  931. EntityJson = "{""id"":" & JsonLite_Quote("" & rs(0)) & ",""namespace_id"":" & JsonLite_Quote("" & rs(1)) & ",""type"":" & JsonLite_Quote("" & rs(2)) & _
  932. ",""canonical_key"":" & JsonLite_Quote("" & rs(3)) & ",""name"":" & JsonLite_Quote("" & rs(4)) & ",""aliases"":" & JRaw(rs(5), "[]") & _
  933. ",""description"":" & JStr(rs(6)) & ",""properties"":" & JRaw(rs(7), "{}") & ",""created_by"":" & JStr(rs(8)) & _
  934. ",""created_at"":" & JStr(rs(9)) & ",""updated_at"":" & JStr(rs(10)) & "}"
  935. End Function
  936. Private Function EntityById(id)
  937. Dim rs
  938. EntityById = "null"
  939. Set rs = DAL().Query(EntitySelect() & " WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  940. If Not rs.EOF Then
  941. EntityById = EntityJson(rs)
  942. End If
  943. rs.Close
  944. End Function
  945. Private Function IsEntityType(t)
  946. Dim re
  947. Set re = New RegExp
  948. re.Pattern = "^[a-z][a-z0-9_-]{0,39}$"
  949. re.IgnoreCase = False
  950. IsEntityType = re.Test(t)
  951. End Function
  952. ' Reads {"kind","id"} from input(name) into kind/id; adds a validation message when it is missing or malformed.
  953. Private Sub ReadEndpoint(input, name, ByRef kind, ByRef id)
  954. Dim o
  955. kind = ""
  956. id = ""
  957. If Not input.HasRaw(name) Then
  958. AddErr name & " is required: an object with kind (entity, memory or document) and id."
  959. Exit Sub
  960. End If
  961. If Left(input.Raw(name), 1) <> "{" Then
  962. AddErr name & " must be an object with kind and id."
  963. Exit Sub
  964. End If
  965. Set o = JsonLite_Parse(input.Raw(name))
  966. If o Is Nothing Then
  967. AddErr name & " must be an object with kind and id."
  968. Exit Sub
  969. End If
  970. If o.Exists("kind") Then
  971. kind = LCase("" & o.Item("kind"))
  972. End If
  973. If o.Exists("id") Then
  974. id = "" & o.Item("id")
  975. End If
  976. If Not Graph_IsKind(kind) Then
  977. AddErr name & ".kind must be entity, memory or document."
  978. kind = ""
  979. id = ""
  980. ElseIf Not Api_IsId(id) Then
  981. AddErr name & ".id must be a valid id."
  982. kind = ""
  983. id = ""
  984. End If
  985. End Sub
  986. Private Function OptInt(input, name, dflt, lo, hi)
  987. Dim v
  988. OptInt = dflt
  989. If Not input.Exists(name) Then
  990. Exit Function
  991. End If
  992. v = input.Item(name)
  993. If IsNull(v) Then
  994. Exit Function
  995. End If
  996. If VarType(v) <> vbDouble Then
  997. AddErr name & " must be a whole number from " & lo & " to " & hi & "."
  998. Exit Function
  999. End If
  1000. If v <> Int(v) Or v < lo Or v > hi Then
  1001. AddErr name & " must be a whole number from " & lo & " to " & hi & "."
  1002. Exit Function
  1003. End If
  1004. OptInt = CLng(v)
  1005. End Function
  1006. Private Function OptTimestamp(input, name)
  1007. Dim v, re
  1008. OptTimestamp = Null
  1009. v = OptString(input, name, 19)
  1010. If IsNull(v) Then
  1011. Exit Function
  1012. End If
  1013. Set re = New RegExp
  1014. re.Pattern = "^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$"
  1015. If Not re.Test(v) Then
  1016. AddErr name & " must be a UTC time like 2027-01-31 18:00:00."
  1017. Exit Function
  1018. End If
  1019. OptTimestamp = v
  1020. End Function
  1021. Private Function AliasesJson(input)
  1022. Dim arr, i, out, t
  1023. AliasesJson = Null
  1024. If Not input.HasRaw("aliases") Then
  1025. If input.Exists("aliases") Then
  1026. If Not IsNull(input.Item("aliases")) Then
  1027. AddErr "aliases must be an array of strings."
  1028. End If
  1029. End If
  1030. Exit Function
  1031. End If
  1032. arr = JsonLite_ParseStringArray(input.Raw("aliases"))
  1033. If IsNull(arr) Then
  1034. AddErr "aliases must be an array of strings."
  1035. Exit Function
  1036. End If
  1037. If UBound(arr) > 31 Then
  1038. AddErr "aliases may contain at most 32 entries."
  1039. Exit Function
  1040. End If
  1041. out = ""
  1042. For i = 0 To UBound(arr)
  1043. t = Trim(arr(i))
  1044. If Len(t) = 0 Or Len(t) > 200 Then
  1045. AddErr "each alias must be 1 to 200 characters."
  1046. Exit Function
  1047. End If
  1048. If i > 0 Then
  1049. out = out & ","
  1050. End If
  1051. out = out & JsonLite_Quote(t)
  1052. Next
  1053. AliasesJson = "[" & out & "]"
  1054. End Function
  1055. Private Function JStr(v)
  1056. If IsNull(v) Then
  1057. JStr = "null"
  1058. ElseIf IsEmpty(v) Then
  1059. JStr = "null"
  1060. Else
  1061. JStr = JsonLite_Quote("" & v)
  1062. End If
  1063. End Function
  1064. Private Function JNum(v)
  1065. If IsNull(v) Then
  1066. JNum = "null"
  1067. ElseIf Len("" & v) = 0 Then
  1068. JNum = "null"
  1069. Else
  1070. JNum = JsonLite_Num(v)
  1071. End If
  1072. End Function
  1073. Private Function JRaw(v, dflt)
  1074. If IsNull(v) Then
  1075. JRaw = dflt
  1076. ElseIf Len("" & v) = 0 Then
  1077. JRaw = dflt
  1078. Else
  1079. JRaw = "" & v
  1080. End If
  1081. End Function
  1082. Private Sub AddErr(msg)
  1083. If Len(m_errs) > 0 Then
  1084. m_errs = m_errs & Chr(30)
  1085. End If
  1086. m_errs = m_errs & msg
  1087. End Sub
  1088. Private Function ReqString(input, name, maxLen)
  1089. Dim v
  1090. ReqString = ""
  1091. If Not input.Exists(name) Then
  1092. AddErr name & " is required."
  1093. Exit Function
  1094. End If
  1095. v = input.Item(name)
  1096. If IsNull(v) Then
  1097. AddErr name & " is required."
  1098. Exit Function
  1099. End If
  1100. If VarType(v) <> vbString Then
  1101. AddErr name & " must be a string."
  1102. Exit Function
  1103. End If
  1104. v = Trim(v)
  1105. If Len(v) = 0 Then
  1106. AddErr name & " must not be empty."
  1107. Exit Function
  1108. End If
  1109. If Len(v) > maxLen Then
  1110. AddErr name & " must be at most " & maxLen & " characters."
  1111. Exit Function
  1112. End If
  1113. ReqString = v
  1114. End Function
  1115. Private Function OptString(input, name, maxLen)
  1116. Dim v
  1117. OptString = Null
  1118. If Not input.Exists(name) Then
  1119. Exit Function
  1120. End If
  1121. v = input.Item(name)
  1122. If IsNull(v) Then
  1123. Exit Function
  1124. End If
  1125. If VarType(v) <> vbString Then
  1126. AddErr name & " must be a string."
  1127. Exit Function
  1128. End If
  1129. If Len(v) > maxLen Then
  1130. AddErr name & " must be at most " & maxLen & " characters."
  1131. Exit Function
  1132. End If
  1133. OptString = v
  1134. End Function
  1135. Private Function OptUnit(input, name)
  1136. Dim v
  1137. OptUnit = Null
  1138. If Not input.Exists(name) Then
  1139. Exit Function
  1140. End If
  1141. v = input.Item(name)
  1142. If IsNull(v) Then
  1143. Exit Function
  1144. End If
  1145. If VarType(v) <> vbDouble Then
  1146. AddErr name & " must be a number between 0 and 1."
  1147. Exit Function
  1148. End If
  1149. If v < 0 Or v > 1 Then
  1150. AddErr name & " must be between 0 and 1."
  1151. Exit Function
  1152. End If
  1153. OptUnit = v
  1154. End Function
  1155. ' Optional JSON object stored as raw text (max 16 KB), or Null
  1156. Private Function ObjectJson(input, name)
  1157. Dim raw
  1158. ObjectJson = Null
  1159. If Not input.HasRaw(name) Then
  1160. If input.Exists(name) Then
  1161. If Not IsNull(input.Item(name)) Then
  1162. AddErr name & " must be a JSON object."
  1163. End If
  1164. End If
  1165. Exit Function
  1166. End If
  1167. raw = input.Raw(name)
  1168. If Left(raw, 1) <> "{" Then
  1169. AddErr name & " must be a JSON object."
  1170. Exit Function
  1171. End If
  1172. If Len(raw) > 16384 Then
  1173. AddErr name & " must be at most 16 KB."
  1174. Exit Function
  1175. End If
  1176. ObjectJson = raw
  1177. End Function
  1178. ' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls and shared call sites)
  1179. Public Sub Invoke(actionName, args)
  1180. Select Case LCase(actionName)
  1181. Case "createentity" : CreateEntity
  1182. Case "entities" : Entities
  1183. Case "entity" : Entity args(0)
  1184. Case "updateentity" : UpdateEntity args(0)
  1185. Case "deleteentity" : DeleteEntity args(0)
  1186. Case "relate" : Relate
  1187. Case "relationships" : Relationships
  1188. Case "relationship" : Relationship args(0)
  1189. Case "review" : Review args(0)
  1190. Case "deleterelationship" : DeleteRelationship args(0)
  1191. Case "traverse" : Traverse
  1192. Case Else
  1193. Err.Raise 438, "ApiGraphController_Class", "Action '" & actionName & "' not found"
  1194. End Select
  1195. End Sub
  1196. End Class
  1197. Dim ApiGraphController_Class__Singleton
  1198. Function ApiGraphController()
  1199. If IsEmpty(ApiGraphController_Class__Singleton) Then
  1200. Set ApiGraphController_Class__Singleton = New ApiGraphController_Class
  1201. End If
  1202. Set ApiGraphController = ApiGraphController_Class__Singleton
  1203. End Function
  1204. ' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller)
  1205. Sub ApiGraphController_Invoke(actionName, args)
  1206. ApiGraphController().Invoke actionName, args
  1207. End Sub
  1208. %>

Powered by TurnKey Linux.