Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

749 lines
30KB

  1. <%
  2. ' ApiMemoriesController: canonical memory records (spec FR-001..FR-005, FR-011, FR-015).
  3. ' Stateless JSON API, no layout. Helpers (auth, errors, idempotency) are in core/lib.Api.asp.
  4. '
  5. ' POST /api/v1/remember Remember create a memory (Idempotency-Key supported; exact duplicates detected)
  6. ' GET /api/v1/memories Recent list/filter, newest first, cursor pagination
  7. ' GET /api/v1/memories/:id Fetch one memory (?revision=n for an older revision)
  8. ' PATCH /api/v1/memories/:id Correct new revision; needs If-Match: <current revision> (or "expected_revision")
  9. ' DELETE /api/v1/memories/:id Forget permanent delete incl. revision history
  10. ' POST /api/v1/memories/:id/retire Retire exclude from ordinary retrieval
  11. ' GET /api/v1/memories/:id/versions Versions revision history
  12. '
  13. ' Permissions on the memory's namespace: read (Fetch/Recent/Versions), write (Remember/Correct/Retire), delete (Forget).
  14. ' Anything the caller may not see is a 404.
  15. Class ApiMemoriesController_Class
  16. Private m_errs
  17. Public Property Get useLayout()
  18. useLayout = False
  19. End Property
  20. Public Property Let useLayout(v)
  21. End Property
  22. Public Property Get Title()
  23. Title = "Memories API"
  24. End Property
  25. '---------------------------------------------------------------
  26. ' POST /api/v1/remember
  27. '---------------------------------------------------------------
  28. Public Sub Remember()
  29. Dim body, input, idemKey, reqHash, nsId, memType, title, content, summary, tagsRaw, attrRaw
  30. Dim confidence, importance, hash, memId, revId, ts, resp, rs, errs, k, warnings
  31. If Not Api_Authenticate() Then Exit Sub
  32. body = Api_ReadBody()
  33. If IsEmpty(body) Then Exit Sub
  34. Set input = JsonLite_Parse(body)
  35. idemKey = Api_Header("Idempotency-Key")
  36. If Len(idemKey) > 200 Then
  37. Api_Error 400, "invalid_idempotency_key", "Idempotency-Key must be at most 200 characters."
  38. Exit Sub
  39. End If
  40. reqHash = Api_Sha256(body)
  41. If Not Api_IdempotencyGate(idemKey, reqHash) Then Exit Sub
  42. m_errs = ""
  43. nsId = ReqString(input, "namespace_id", 64)
  44. memType = ReqString(input, "type", 40)
  45. title = ReqString(input, "title", 200)
  46. content = ReqString(input, "content", 100000)
  47. summary = OptString(input, "summary", 2000)
  48. tagsRaw = TagsJson(input)
  49. attrRaw = AttributesJson(input)
  50. confidence = OptUnit(input, "confidence")
  51. importance = OptUnit(input, "importance")
  52. If Len(m_errs) > 0 Then
  53. Api_Invalid Split(m_errs, Chr(30))
  54. Exit Sub
  55. End If
  56. ' Concealment: a namespace the caller cannot write to looks the same as one that does not exist.
  57. If Not Api_CanAccessNamespace(nsId, "write") Then
  58. Api_Audit "memory.remember", "namespace", nsId, "denied"
  59. Api_Error 404, "namespace_not_found", "Namespace not found."
  60. Exit Sub
  61. End If
  62. Set rs = DAL().Query("SELECT 1 FROM memory_types WHERE code = ?", memType)
  63. If rs.EOF Then
  64. rs.Close
  65. Api_Invalid Array("type '" & memType & "' is not a known memory type.")
  66. Exit Sub
  67. End If
  68. rs.Close
  69. hash = Api_Sha256(nsId & "|" & memType & "|" & title & "|" & content)
  70. ' Exact duplicate of an active memory in the same namespace: return it instead of creating another.
  71. Set rs = DAL().Query("SELECT m.id, m.current_revision, r.verification_status FROM memories m " & _
  72. "JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = m.current_revision " & _
  73. "WHERE m.tenant_id = ? AND m.namespace_id = ? AND m.type = ? AND m.lifecycle_status = 'active' AND r.content_hash = ?", _
  74. Array(Api_TenantId, nsId, memType, hash))
  75. If Not rs.EOF Then
  76. resp = "{""id"":" & JsonLite_Quote("" & rs(0)) & ",""revision"":" & CLng(rs(1)) & ",""status"":""active"",""verification_status"":" & _
  77. JsonLite_Quote("" & rs(2)) & ",""indexing_status"":""not_indexed"",""duplicate"":true}"
  78. rs.Close
  79. StoreIdem idemKey, reqHash, 200, resp
  80. Api_Send 200, resp
  81. Exit Sub
  82. End If
  83. rs.Close
  84. memId = Api_NewId()
  85. revId = Api_NewId()
  86. ts = Api_Now()
  87. On Error Resume Next
  88. DAL().BeginTransaction
  89. DAL().Execute "INSERT INTO memories (id, tenant_id, namespace_id, type, current_revision, lifecycle_status, creator_principal_id, created_at, updated_at) " & _
  90. "VALUES (?, ?, ?, ?, 1, 'active', ?, ?, ?)", Array(memId, Api_TenantId, nsId, memType, Api_PrincipalId, ts, ts)
  91. InsertRevision revId, memId, 1, title, summary, content, attrRaw, tagsRaw, confidence, importance, hash, "created", ts
  92. resp = "{""id"":" & JsonLite_Quote(memId) & ",""revision"":1,""status"":""active"",""verification_status"":""unverified"",""indexing_status"":""not_indexed"",""duplicate"":false}"
  93. StoreIdem idemKey, reqHash, 201, resp
  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 "memory.remember", "memory", memId, "ok"
  108. Response.AddHeader "Location", "/api/v1/memories/" & memId
  109. Api_Send 201, resp
  110. End Sub
  111. '---------------------------------------------------------------
  112. ' GET /api/v1/memories ?namespace_id= &type= &status=active|retired|superseded|all &verification_status= &limit= &cursor=
  113. '---------------------------------------------------------------
  114. Public Sub Recent()
  115. Dim nsId, memType, status, ver, lim, cursor, allowed, sql, params(), n, rs, out, count, lastTs, lastId, p, cts, cid, nextCursor
  116. If Not Api_Authenticate() Then Exit Sub
  117. nsId = Trim("" & Request.QueryString("namespace_id"))
  118. memType = Trim("" & Request.QueryString("type"))
  119. status = LCase(Trim("" & Request.QueryString("status")))
  120. ver = LCase(Trim("" & Request.QueryString("verification_status")))
  121. lim = Api_ToInt(Request.QueryString("limit"), 20, 1, 100)
  122. cursor = Trim("" & Request.QueryString("cursor"))
  123. If Len(status) = 0 Then status = "active"
  124. If status <> "active" And status <> "retired" And status <> "superseded" And status <> "all" Then
  125. Api_Invalid Array("status must be active, retired, superseded or all.")
  126. Exit Sub
  127. End If
  128. If Len(ver) > 0 And ver <> "unverified" And ver <> "verified" And ver <> "disputed" And ver <> "rejected" Then
  129. Api_Invalid Array("verification_status must be unverified, verified, disputed or rejected.")
  130. Exit Sub
  131. End If
  132. If Len(nsId) > 0 Then
  133. If Not Api_CanAccessNamespace(nsId, "read") Then
  134. Api_Error 404, "namespace_not_found", "Namespace not found."
  135. Exit Sub
  136. End If
  137. allowed = "'" & nsId & "'"
  138. Else
  139. allowed = Api_AllowedNamespaceIds("read")
  140. End If
  141. If Len(allowed) = 0 Then
  142. Api_Send 200, "{""data"":[],""next_cursor"":null}"
  143. Exit Sub
  144. End If
  145. sql = MemorySelect() & " WHERE m.tenant_id = ? AND m.namespace_id IN (" & allowed & ")"
  146. ReDim params(0)
  147. params(0) = Api_TenantId
  148. n = 1
  149. If Len(memType) > 0 Then
  150. sql = sql & " AND m.type = ?"
  151. ReDim Preserve params(n)
  152. params(n) = memType
  153. n = n + 1
  154. End If
  155. If status <> "all" Then
  156. sql = sql & " AND m.lifecycle_status = ?"
  157. ReDim Preserve params(n)
  158. params(n) = status
  159. n = n + 1
  160. End If
  161. If Len(ver) > 0 Then
  162. sql = sql & " AND r.verification_status = ?"
  163. ReDim Preserve params(n)
  164. params(n) = ver
  165. n = n + 1
  166. End If
  167. If Len(cursor) > 0 Then
  168. p = InStr(cursor, "|")
  169. cts = ""
  170. cid = ""
  171. If p > 0 Then
  172. cts = Left(cursor, p - 1)
  173. cid = Mid(cursor, p + 1)
  174. End If
  175. If Len(cts) = 0 Or Not Api_IsId(cid) Then
  176. Api_Error 400, "invalid_cursor", "The cursor is not valid."
  177. Exit Sub
  178. End If
  179. sql = sql & " AND (m.created_at < ? OR (m.created_at = ? AND m.id < ?))"
  180. ReDim Preserve params(n + 2)
  181. params(n) = cts
  182. params(n + 1) = cts
  183. params(n + 2) = cid
  184. n = n + 3
  185. End If
  186. ' G3DB accepts at most 8 parameters (tenant + type + status + verification + 3 cursor = 7)
  187. sql = sql & " ORDER BY m.created_at DESC, m.id DESC LIMIT " & (lim + 1)
  188. Set rs = DAL().Query(sql, params)
  189. out = ""
  190. count = 0
  191. lastTs = ""
  192. lastId = ""
  193. nextCursor = "null"
  194. Do While Not rs.EOF
  195. If count >= lim Then
  196. nextCursor = JsonLite_Quote(lastTs & "|" & lastId)
  197. Exit Do
  198. End If
  199. If count > 0 Then out = out & ","
  200. out = out & MemoryJson(rs, True)
  201. lastTs = "" & rs(8)
  202. lastId = "" & rs(0)
  203. count = count + 1
  204. rs.MoveNext
  205. Loop
  206. rs.Close
  207. Api_Send 200, "{""data"":[" & out & "],""next_cursor"":" & nextCursor & "}"
  208. End Sub
  209. '---------------------------------------------------------------
  210. ' GET /api/v1/memories/:id (?revision=n)
  211. '---------------------------------------------------------------
  212. Public Sub Fetch(id)
  213. Dim rs, nsId, revParam, rev, json
  214. If Not Api_Authenticate() Then Exit Sub
  215. If Not Api_IsId(id) Then
  216. Api_NotFound
  217. Exit Sub
  218. End If
  219. ' The row is copied out and the result set closed BEFORE the permission check: a second query while a
  220. ' result set is still open hangs the request under G3DB/SQLite (script timeout).
  221. Set rs = DAL().Query(MemorySelect() & " WHERE m.id = ? AND m.tenant_id = ?", Array(id, Api_TenantId))
  222. If rs.EOF Then
  223. rs.Close
  224. Api_NotFound
  225. Exit Sub
  226. End If
  227. nsId = "" & rs(1)
  228. json = MemoryJson(rs, False)
  229. rs.Close
  230. If Not Api_CanAccessNamespace(nsId, "read") Then
  231. Api_NotFound
  232. Exit Sub
  233. End If
  234. revParam = Trim("" & Request.QueryString("revision"))
  235. If Len(revParam) = 0 Then
  236. Api_Send 200, "{""data"":" & json & "}"
  237. Exit Sub
  238. End If
  239. If Not IsNumeric(revParam) Then
  240. Api_Invalid Array("revision must be a positive integer.")
  241. Exit Sub
  242. End If
  243. rev = CLng(revParam)
  244. Set rs = DAL().Query(MemorySelectRevision() & " WHERE m.id = ? AND m.tenant_id = ?", Array(rev, id, Api_TenantId))
  245. If rs.EOF Then
  246. rs.Close
  247. Api_NotFound
  248. Exit Sub
  249. End If
  250. json = MemoryJson(rs, False)
  251. rs.Close
  252. Api_Send 200, "{""data"":" & json & "}"
  253. End Sub
  254. '---------------------------------------------------------------
  255. ' PATCH /api/v1/memories/:id creates revision n+1 (unverified)
  256. '---------------------------------------------------------------
  257. Public Sub Correct(id)
  258. Dim body, input, rs, nsId, curRev, expected, ifMatch, lifecycle
  259. Dim title, content, summary, tagsRaw, attrRaw, confidence, importance, reason, hash, ts, newRev, memType, k, resp
  260. Dim hasTitle, hasContent, hasSummary, hasTags, hasAttr, hasConf, hasImp
  261. If Not Api_Authenticate() Then Exit Sub
  262. If Not Api_IsId(id) Then
  263. Api_NotFound
  264. Exit Sub
  265. End If
  266. body = Api_ReadBody()
  267. If IsEmpty(body) Then Exit Sub
  268. Set input = JsonLite_Parse(body)
  269. Set rs = DAL().Query("SELECT m.namespace_id, m.current_revision, m.lifecycle_status, m.type, r.title, r.summary, r.content, r.attributes, r.tags, r.confidence, r.importance " & _
  270. "FROM memories m JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = m.current_revision " & _
  271. "WHERE m.id = ? AND m.tenant_id = ?", Array(id, Api_TenantId))
  272. If rs.EOF Then
  273. rs.Close
  274. Api_NotFound
  275. Exit Sub
  276. End If
  277. nsId = "" & rs(0)
  278. curRev = CLng(rs(1))
  279. lifecycle = "" & rs(2)
  280. memType = "" & rs(3)
  281. title = rs(4)
  282. summary = rs(5)
  283. content = rs(6)
  284. attrRaw = rs(7)
  285. tagsRaw = rs(8)
  286. confidence = rs(9)
  287. importance = rs(10)
  288. rs.Close
  289. If Not Api_CanAccessNamespace(nsId, "write") Then
  290. Api_NotFound
  291. Exit Sub
  292. End If
  293. ' Optimistic concurrency: the caller must say which revision they edited.
  294. ifMatch = Replace(Replace(Api_Header("If-Match"), """", ""), "W/", "")
  295. expected = ifMatch
  296. If Len(expected) = 0 And input.Exists("expected_revision") Then expected = "" & input.Item("expected_revision")
  297. If Len(expected) = 0 Then
  298. Api_Error 428, "precondition_required", "Send If-Match: <current revision> (or ""expected_revision"" in the body)."
  299. Exit Sub
  300. End If
  301. If Not IsNumeric(expected) Then
  302. Api_Error 400, "invalid_revision", "If-Match / expected_revision must be a revision number."
  303. Exit Sub
  304. End If
  305. If CLng(expected) <> curRev Then
  306. Response.AddHeader "ETag", """" & curRev & """"
  307. Api_Error 412, "stale_revision", "The memory is at revision " & curRev & ", not " & CLng(expected) & ". Re-read it and retry."
  308. Exit Sub
  309. End If
  310. If lifecycle <> "active" Then
  311. Api_Error 409, "not_active", "A " & lifecycle & " memory cannot be corrected."
  312. Exit Sub
  313. End If
  314. m_errs = ""
  315. hasTitle = input.Exists("title")
  316. hasContent = input.Exists("content")
  317. hasSummary = input.Exists("summary")
  318. hasTags = input.Exists("tags") Or input.HasRaw("tags")
  319. hasAttr = input.Exists("attributes") Or input.HasRaw("attributes")
  320. hasConf = input.Exists("confidence")
  321. hasImp = input.Exists("importance")
  322. If hasTitle Then title = ReqString(input, "title", 200)
  323. If hasContent Then content = ReqString(input, "content", 100000)
  324. If hasSummary Then summary = OptString(input, "summary", 2000)
  325. If hasTags Then tagsRaw = TagsJson(input)
  326. If hasAttr Then attrRaw = AttributesJson(input)
  327. If hasConf Then confidence = OptUnit(input, "confidence")
  328. If hasImp Then importance = OptUnit(input, "importance")
  329. reason = OptString(input, "change_reason", 500)
  330. If Not (hasTitle Or hasContent Or hasSummary Or hasTags Or hasAttr Or hasConf Or hasImp) Then
  331. m_errs = m_errs & Chr(30) & "Send at least one field to change."
  332. End If
  333. If Left(m_errs, 1) = Chr(30) Then m_errs = Mid(m_errs, 2)
  334. If Len(m_errs) > 0 Then
  335. Api_Invalid Split(m_errs, Chr(30))
  336. Exit Sub
  337. End If
  338. If IsNull(reason) Or Len("" & reason) = 0 Then reason = "corrected"
  339. hash = Api_Sha256(nsId & "|" & memType & "|" & title & "|" & content)
  340. ts = Api_Now()
  341. newRev = curRev + 1
  342. On Error Resume Next
  343. DAL().BeginTransaction
  344. InsertRevision Api_NewId(), id, newRev, title, summary, content, attrRaw, tagsRaw, confidence, importance, hash, reason, ts
  345. DAL().Execute "UPDATE memories SET current_revision = ?, updated_at = ? WHERE id = ? AND tenant_id = ? AND current_revision = ?", _
  346. Array(newRev, ts, id, Api_TenantId, curRev)
  347. If Err.Number <> 0 Then
  348. k = Err.Number : Api_NoteDbError
  349. DAL().RollbackTransaction
  350. Api_DbFailed k, ""
  351. Exit Sub
  352. End If
  353. DAL().CommitTransaction
  354. If Err.Number <> 0 Then
  355. k = Err.Number : Api_NoteDbError
  356. Api_DbFailed k, ""
  357. Exit Sub
  358. End If
  359. On Error GoTo 0
  360. Api_Audit "memory.correct", "memory", id, "ok"
  361. Response.AddHeader "ETag", """" & newRev & """"
  362. resp = "{""id"":" & JsonLite_Quote(id) & ",""revision"":" & newRev & ",""status"":""active"",""verification_status"":""unverified"",""indexing_status"":""not_indexed""}"
  363. Api_Send 200, resp
  364. End Sub
  365. '---------------------------------------------------------------
  366. ' DELETE /api/v1/memories/:id
  367. '---------------------------------------------------------------
  368. Public Sub Forget(id)
  369. Dim rs, nsId, k
  370. If Not Api_Authenticate() Then Exit Sub
  371. If Not Api_IsId(id) Then
  372. Api_NotFound
  373. Exit Sub
  374. End If
  375. Set rs = DAL().Query("SELECT namespace_id FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  376. If rs.EOF Then
  377. rs.Close
  378. Api_NotFound
  379. Exit Sub
  380. End If
  381. nsId = "" & rs(0)
  382. rs.Close
  383. If Not Api_CanAccessNamespace(nsId, "delete") Then
  384. Api_Audit "memory.forget", "memory", id, "denied"
  385. Api_NotFound
  386. Exit Sub
  387. End If
  388. On Error Resume Next
  389. DAL().BeginTransaction
  390. DAL().Execute "DELETE FROM memory_revisions WHERE memory_id = ?", id
  391. DAL().Execute "DELETE FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)
  392. If Err.Number <> 0 Then
  393. k = Err.Number : Api_NoteDbError
  394. DAL().RollbackTransaction
  395. Api_DbFailed k, ""
  396. Exit Sub
  397. End If
  398. DAL().CommitTransaction
  399. On Error GoTo 0
  400. Api_Audit "memory.forget", "memory", id, "ok"
  401. Api_Send 200, "{""deleted"":true,""id"":" & JsonLite_Quote(id) & "}"
  402. End Sub
  403. '---------------------------------------------------------------
  404. ' POST /api/v1/memories/:id/retire
  405. '---------------------------------------------------------------
  406. Public Sub Retire(id)
  407. Dim rs, nsId, k
  408. If Not Api_Authenticate() Then Exit Sub
  409. If Not Api_IsId(id) Then
  410. Api_NotFound
  411. Exit Sub
  412. End If
  413. Set rs = DAL().Query("SELECT namespace_id FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  414. If rs.EOF Then
  415. rs.Close
  416. Api_NotFound
  417. Exit Sub
  418. End If
  419. nsId = "" & rs(0)
  420. rs.Close
  421. If Not Api_CanAccessNamespace(nsId, "write") Then
  422. Api_NotFound
  423. Exit Sub
  424. End If
  425. On Error Resume Next
  426. DAL().Execute "UPDATE memories SET lifecycle_status = 'retired', updated_at = ? WHERE id = ? AND tenant_id = ?", Array(Api_Now(), id, Api_TenantId)
  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 "memory.retire", "memory", id, "ok"
  434. Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""status"":""retired""}"
  435. End Sub
  436. '---------------------------------------------------------------
  437. ' GET /api/v1/memories/:id/versions
  438. '---------------------------------------------------------------
  439. Public Sub Versions(id)
  440. Dim rs, nsId, out, count
  441. If Not Api_Authenticate() Then Exit Sub
  442. If Not Api_IsId(id) Then
  443. Api_NotFound
  444. Exit Sub
  445. End If
  446. Set rs = DAL().Query("SELECT namespace_id FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  447. If rs.EOF Then
  448. rs.Close
  449. Api_NotFound
  450. Exit Sub
  451. End If
  452. nsId = "" & rs(0)
  453. rs.Close
  454. If Not Api_CanAccessNamespace(nsId, "read") Then
  455. Api_NotFound
  456. Exit Sub
  457. End If
  458. Set rs = DAL().Query("SELECT revision, title, summary, content, tags, confidence, importance, verification_status, change_reason, created_by, created_at " & _
  459. "FROM memory_revisions WHERE memory_id = ? ORDER BY revision DESC", id)
  460. out = ""
  461. count = 0
  462. Do While Not rs.EOF
  463. If count > 0 Then out = out & ","
  464. out = out & "{""revision"":" & CLng(rs(0)) & ",""title"":" & JsonLite_Quote("" & rs(1)) & ",""summary"":" & JStr(rs(2)) & _
  465. ",""content"":" & JsonLite_Quote("" & rs(3)) & ",""tags"":" & JRaw(rs(4), "[]") & ",""confidence"":" & JNum(rs(5)) & _
  466. ",""importance"":" & JNum(rs(6)) & ",""verification_status"":" & JsonLite_Quote("" & rs(7)) & _
  467. ",""change_reason"":" & JStr(rs(8)) & ",""created_by"":" & JsonLite_Quote("" & rs(9)) & ",""created_at"":" & JsonLite_Quote("" & rs(10)) & "}"
  468. count = count + 1
  469. rs.MoveNext
  470. Loop
  471. rs.Close
  472. Api_Send 200, "{""data"":[" & out & "]}"
  473. End Sub
  474. '===============================================================
  475. ' Helpers
  476. '===============================================================
  477. ' Memory + current revision. Column order is relied on by MemoryJson:
  478. ' 0 id, 1 namespace_id, 2 type, 3 current_revision, 4 lifecycle_status, 5 valid_from, 6 valid_until, 7 creator, 8 created_at, 9 updated_at,
  479. ' 10 revision, 11 title, 12 summary, 13 content, 14 attributes, 15 tags, 16 confidence, 17 importance, 18 verification_status, 19 change_reason
  480. Private Function MemorySelect()
  481. MemorySelect = "SELECT m.id, m.namespace_id, m.type, m.current_revision, m.lifecycle_status, m.valid_from, m.valid_until, m.creator_principal_id, m.created_at, m.updated_at, " & _
  482. "r.revision, r.title, r.summary, r.content, r.attributes, r.tags, r.confidence, r.importance, r.verification_status, r.change_reason " & _
  483. "FROM memories m JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = m.current_revision"
  484. End Function
  485. ' Same columns but a specific revision (first parameter is the revision number)
  486. Private Function MemorySelectRevision()
  487. MemorySelectRevision = "SELECT m.id, m.namespace_id, m.type, m.current_revision, m.lifecycle_status, m.valid_from, m.valid_until, m.creator_principal_id, m.created_at, m.updated_at, " & _
  488. "r.revision, r.title, r.summary, r.content, r.attributes, r.tags, r.confidence, r.importance, r.verification_status, r.change_reason " & _
  489. "FROM memories m JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = ?"
  490. End Function
  491. Private Function MemoryJson(rs, brief)
  492. Dim s
  493. s = "{""id"":" & JsonLite_Quote("" & rs(0)) & ",""namespace_id"":" & JsonLite_Quote("" & rs(1)) & ",""type"":" & JsonLite_Quote("" & rs(2)) & _
  494. ",""status"":" & JsonLite_Quote("" & rs(4)) & ",""current_revision"":" & CLng(rs(3)) & ",""revision"":" & CLng(rs(10)) & _
  495. ",""verification_status"":" & JsonLite_Quote("" & rs(18)) & ",""title"":" & JsonLite_Quote("" & rs(11)) & ",""summary"":" & JStr(rs(12))
  496. If Not brief Then
  497. s = s & ",""content"":" & JsonLite_Quote("" & rs(13)) & ",""attributes"":" & JRaw(rs(14), "null") & ",""change_reason"":" & JStr(rs(19)) & _
  498. ",""valid_from"":" & JStr(rs(5)) & ",""valid_until"":" & JStr(rs(6)) & ",""created_by"":" & JsonLite_Quote("" & rs(7))
  499. End If
  500. s = s & ",""tags"":" & JRaw(rs(15), "[]") & ",""confidence"":" & JNum(rs(16)) & ",""importance"":" & JNum(rs(17)) & _
  501. ",""created_at"":" & JsonLite_Quote("" & rs(8)) & ",""updated_at"":" & JsonLite_Quote("" & rs(9)) & "}"
  502. MemoryJson = s
  503. End Function
  504. Private Function JStr(v)
  505. If IsNull(v) Then
  506. JStr = "null"
  507. Else
  508. JStr = JsonLite_Quote("" & v)
  509. End If
  510. End Function
  511. Private Function JNum(v)
  512. If IsNull(v) Then
  513. JNum = "null"
  514. ElseIf Len("" & v) = 0 Then
  515. JNum = "null"
  516. Else
  517. JNum = JsonLite_Num(v)
  518. End If
  519. End Function
  520. ' Stored raw JSON text (validated on the way in) or a default
  521. Private Function JRaw(v, dflt)
  522. If IsNull(v) Then
  523. JRaw = dflt
  524. ElseIf Len("" & v) = 0 Then
  525. JRaw = dflt
  526. Else
  527. JRaw = "" & v
  528. End If
  529. End Function
  530. Private Sub AddErr(msg)
  531. If Len(m_errs) > 0 Then m_errs = m_errs & Chr(30)
  532. m_errs = m_errs & msg
  533. End Sub
  534. Private Function ReqString(input, name, maxLen)
  535. Dim v
  536. ReqString = ""
  537. If Not input.Exists(name) Then
  538. AddErr name & " is required."
  539. Exit Function
  540. End If
  541. v = input.Item(name)
  542. If IsNull(v) Then
  543. AddErr name & " is required."
  544. Exit Function
  545. End If
  546. If VarType(v) <> vbString Then
  547. AddErr name & " must be a string."
  548. Exit Function
  549. End If
  550. v = Trim(v)
  551. If Len(v) = 0 Then
  552. AddErr name & " must not be empty."
  553. Exit Function
  554. End If
  555. If Len(v) > maxLen Then
  556. AddErr name & " must be at most " & maxLen & " characters."
  557. Exit Function
  558. End If
  559. ReqString = v
  560. End Function
  561. ' Optional string: Null when absent or null
  562. Private Function OptString(input, name, maxLen)
  563. Dim v
  564. OptString = Null
  565. If Not input.Exists(name) Then Exit Function
  566. v = input.Item(name)
  567. If IsNull(v) Then Exit Function
  568. If VarType(v) <> vbString Then
  569. AddErr name & " must be a string."
  570. Exit Function
  571. End If
  572. If Len(v) > maxLen Then
  573. AddErr name & " must be at most " & maxLen & " characters."
  574. Exit Function
  575. End If
  576. OptString = v
  577. End Function
  578. ' Optional number in 0..1: Null when absent or null
  579. Private Function OptUnit(input, name)
  580. Dim v
  581. OptUnit = Null
  582. If Not input.Exists(name) Then Exit Function
  583. v = input.Item(name)
  584. If IsNull(v) Then Exit Function
  585. If VarType(v) <> vbDouble Then
  586. AddErr name & " must be a number between 0 and 1."
  587. Exit Function
  588. End If
  589. If v < 0 Or v > 1 Then
  590. AddErr name & " must be between 0 and 1."
  591. Exit Function
  592. End If
  593. OptUnit = v
  594. End Function
  595. ' tags: optional array of non-empty strings; returns compact JSON text or Null
  596. Private Function TagsJson(input)
  597. Dim arr, i, out, t
  598. TagsJson = Null
  599. If Not input.HasRaw("tags") Then
  600. If input.Exists("tags") Then
  601. If Not IsNull(input.Item("tags")) Then AddErr "tags must be an array of strings."
  602. End If
  603. Exit Function
  604. End If
  605. arr = JsonLite_ParseStringArray(input.Raw("tags"))
  606. If IsNull(arr) Then
  607. AddErr "tags must be an array of strings."
  608. Exit Function
  609. End If
  610. If UBound(arr) > 31 Then
  611. AddErr "tags may contain at most 32 entries."
  612. Exit Function
  613. End If
  614. out = ""
  615. For i = 0 To UBound(arr)
  616. t = Trim(arr(i))
  617. If Len(t) = 0 Or Len(t) > 64 Then
  618. AddErr "each tag must be 1 to 64 characters."
  619. Exit Function
  620. End If
  621. If i > 0 Then out = out & ","
  622. out = out & JsonLite_Quote(t)
  623. Next
  624. TagsJson = "[" & out & "]"
  625. End Function
  626. ' attributes: optional JSON object, stored as its raw text (max 16 KB) or Null
  627. Private Function AttributesJson(input)
  628. Dim raw
  629. AttributesJson = Null
  630. If Not input.HasRaw("attributes") Then
  631. If input.Exists("attributes") Then
  632. If Not IsNull(input.Item("attributes")) Then AddErr "attributes must be a JSON object."
  633. End If
  634. Exit Function
  635. End If
  636. raw = input.Raw("attributes")
  637. If Left(raw, 1) <> "{" Then
  638. AddErr "attributes must be a JSON object."
  639. Exit Function
  640. End If
  641. If Len(raw) > 16384 Then
  642. AddErr "attributes must be at most 16 KB."
  643. Exit Function
  644. End If
  645. AttributesJson = raw
  646. End Function
  647. ' G3DB allows at most 8 parameters per statement, so a revision is written in two steps (same transaction).
  648. Private Sub InsertRevision(revId, memId, revNo, title, summary, content, attrRaw, tagsRaw, confidence, importance, hash, reason, ts)
  649. DAL().Execute "INSERT INTO memory_revisions (id, memory_id, revision, title, content, content_hash, created_by, created_at) " & _
  650. "VALUES (?, ?, ?, ?, ?, ?, ?, ?)", Array(revId, memId, revNo, title, content, hash, Api_PrincipalId, ts)
  651. DAL().Execute "UPDATE memory_revisions SET summary = ?, attributes = ?, tags = ?, confidence = ?, importance = ?, change_reason = ? WHERE id = ?", _
  652. Array(summary, attrRaw, tagsRaw, confidence, importance, reason, revId)
  653. End Sub
  654. Private Sub StoreIdem(idemKey, reqHash, status, resp)
  655. Api_IdempotencyStore idemKey, reqHash, status, resp
  656. End Sub
  657. ' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls and shared call sites)
  658. Public Sub Invoke(actionName, args)
  659. Select Case LCase(actionName)
  660. Case "remember" : Remember
  661. Case "recent" : Recent
  662. Case "fetch" : Fetch args(0)
  663. Case "correct" : Correct args(0)
  664. Case "forget" : Forget args(0)
  665. Case "retire" : Retire args(0)
  666. Case "versions" : Versions args(0)
  667. Case Else
  668. Err.Raise 438, "ApiMemoriesController_Class", "Action '" & actionName & "' not found"
  669. End Select
  670. End Sub
  671. End Class
  672. Dim ApiMemoriesController_Class__Singleton
  673. Function ApiMemoriesController()
  674. If IsEmpty(ApiMemoriesController_Class__Singleton) Then
  675. Set ApiMemoriesController_Class__Singleton = New ApiMemoriesController_Class
  676. End If
  677. Set ApiMemoriesController = ApiMemoriesController_Class__Singleton
  678. End Function
  679. ' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller)
  680. Sub ApiMemoriesController_Invoke(actionName, args)
  681. ApiMemoriesController().Invoke actionName, args
  682. End Sub
  683. %>

Powered by TurnKey Linux.