Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

332 lignes
13KB

  1. <%
  2. ' ApiSessionsController: agent sessions and working-state checkpoints (spec FR-012, AC-09, AC-10).
  3. ' Stateless JSON API, no layout. Helpers (auth, errors, idempotency) are in core/lib.Api.asp.
  4. '
  5. ' POST /api/v1/sessions Start {"namespace_id","objective"} -> 201 {"id","status","revision":0}
  6. ' PUT /api/v1/sessions/:id/state SaveState {"state":{...}} with If-Match: <checkpoint revision> (0 = none yet)
  7. ' GET /api/v1/sessions/:id/state RestoreState latest checkpoint (revision 0 / state null when none)
  8. ' POST /api/v1/sessions/:id/complete Complete {"outcome":"..."} optional
  9. '
  10. ' Permissions on the session's namespace: write (Start/SaveState/Complete), read (RestoreState). Any principal with
  11. ' access to the namespace may resume the session. Stale revisions get 412 and never overwrite a newer checkpoint.
  12. Class ApiSessionsController_Class
  13. Public Property Get useLayout()
  14. useLayout = False
  15. End Property
  16. Public Property Let useLayout(v)
  17. End Property
  18. Public Property Get Title()
  19. Title = "Sessions API"
  20. End Property
  21. '---------------------------------------------------------------
  22. ' POST /api/v1/sessions
  23. '---------------------------------------------------------------
  24. Public Sub Start()
  25. Dim body, input, nsId, objective, idemKey, reqHash, id, ts, resp, k, errs
  26. If Not Api_Authenticate() Then Exit Sub
  27. body = Api_ReadBody()
  28. If IsEmpty(body) Then Exit Sub
  29. Set input = JsonLite_Parse(body)
  30. idemKey = Api_Header("Idempotency-Key")
  31. If Len(idemKey) > 200 Then
  32. Api_Error 400, "invalid_idempotency_key", "Idempotency-Key must be at most 200 characters."
  33. Exit Sub
  34. End If
  35. reqHash = Api_Sha256(body)
  36. If Not Api_IdempotencyGate(idemKey, reqHash) Then Exit Sub
  37. errs = ""
  38. nsId = StringField(input, "namespace_id", 64, errs)
  39. objective = StringField(input, "objective", 2000, errs)
  40. If Len(errs) > 0 Then
  41. Api_Invalid Split(errs, Chr(30))
  42. Exit Sub
  43. End If
  44. If Not Api_CanAccessNamespace(nsId, "write") Then
  45. Api_Error 404, "namespace_not_found", "Namespace not found."
  46. Exit Sub
  47. End If
  48. id = Api_NewId()
  49. ts = Api_Now()
  50. resp = "{""id"":" & JsonLite_Quote(id) & ",""status"":""active"",""revision"":0}"
  51. On Error Resume Next
  52. DAL().BeginTransaction
  53. DAL().Execute "INSERT INTO sessions (id, tenant_id, namespace_id, principal_id, objective, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 'active', ?, ?)", _
  54. Array(id, Api_TenantId, nsId, Api_PrincipalId, objective, ts, ts)
  55. Api_IdempotencyStore idemKey, reqHash, 201, resp
  56. If Err.Number <> 0 Then
  57. k = Err.Number : Api_NoteDbError
  58. DAL().RollbackTransaction
  59. Api_DbFailed k, ""
  60. Exit Sub
  61. End If
  62. DAL().CommitTransaction
  63. On Error GoTo 0
  64. Api_Audit "session.start", "session", id, "ok"
  65. Response.AddHeader "Location", "/api/v1/sessions/" & id
  66. Api_Send 201, resp
  67. End Sub
  68. '---------------------------------------------------------------
  69. ' PUT /api/v1/sessions/:id/state
  70. '---------------------------------------------------------------
  71. Public Sub SaveState(id)
  72. Dim body, input, nsId, status, curRev, ifMatch, expected, rs, stateRaw, ts, newRev, k, resp
  73. If Not Api_Authenticate() Then Exit Sub
  74. If Not Api_IsId(id) Then
  75. Api_NotFound
  76. Exit Sub
  77. End If
  78. body = Api_ReadBody()
  79. If IsEmpty(body) Then Exit Sub
  80. Set input = JsonLite_Parse(body)
  81. If Not LoadSession(id, nsId, status, curRev) Then Exit Sub
  82. If Not Api_CanAccessNamespace(nsId, "write") Then
  83. Api_NotFound
  84. Exit Sub
  85. End If
  86. If status <> "active" Then
  87. Api_Error 409, "session_closed", "The session is " & status & "; its state can no longer change."
  88. Exit Sub
  89. End If
  90. If Not input.HasRaw("state") Then
  91. Api_Invalid Array("state is required and must be a JSON object.")
  92. Exit Sub
  93. End If
  94. stateRaw = input.Raw("state")
  95. If Left(stateRaw, 1) <> "{" Then
  96. Api_Invalid Array("state must be a JSON object.")
  97. Exit Sub
  98. End If
  99. If Len(stateRaw) > 65536 Then
  100. Api_Invalid Array("state must be at most 64 KB.")
  101. Exit Sub
  102. End If
  103. ifMatch = Replace(Replace(Api_Header("If-Match"), """", ""), "W/", "")
  104. expected = ifMatch
  105. If Len(expected) = 0 And input.Exists("expected_revision") Then expected = "" & input.Item("expected_revision")
  106. If Len(expected) = 0 Then
  107. Api_Error 428, "precondition_required", "Send If-Match: <current checkpoint revision> (0 when there is none), or ""expected_revision"" in the body."
  108. Exit Sub
  109. End If
  110. If Not IsNumeric(expected) Then
  111. Api_Error 400, "invalid_revision", "If-Match / expected_revision must be a revision number."
  112. Exit Sub
  113. End If
  114. If CLng(expected) <> curRev Then
  115. Response.AddHeader "ETag", """" & curRev & """"
  116. Api_Error 412, "stale_revision", "The session state is at revision " & curRev & ", not " & CLng(expected) & ". Restore it again before saving."
  117. Exit Sub
  118. End If
  119. newRev = curRev + 1
  120. ts = Api_Now()
  121. On Error Resume Next
  122. ' UNIQUE (session_id, revision) rejects a concurrent writer that passed the check above
  123. DAL().Execute "INSERT INTO checkpoints (id, session_id, revision, state, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?)", _
  124. Array(Api_NewId(), id, newRev, stateRaw, Api_PrincipalId, ts)
  125. If Err.Number <> 0 Then
  126. k = Err.Number : Api_NoteDbError
  127. Err.Clear
  128. On Error GoTo 0
  129. If InStr(LCase(Api_LastDbError), "unique") > 0 Then
  130. Api_Error 412, "stale_revision", "Another checkpoint was saved first. Restore the state again before saving."
  131. Else
  132. Api_DbFailed k, ""
  133. End If
  134. Exit Sub
  135. End If
  136. DAL().Execute "UPDATE sessions SET updated_at = ? WHERE id = ?", Array(ts, id)
  137. On Error GoTo 0
  138. Api_Audit "session.save_state", "session", id, "ok"
  139. Response.AddHeader "ETag", """" & newRev & """"
  140. resp = "{""session_id"":" & JsonLite_Quote(id) & ",""revision"":" & newRev & ",""saved_at"":" & JsonLite_Quote(ts) & "}"
  141. Api_Send 200, resp
  142. End Sub
  143. '---------------------------------------------------------------
  144. ' GET /api/v1/sessions/:id/state
  145. '---------------------------------------------------------------
  146. Public Sub RestoreState(id)
  147. Dim nsId, status, curRev, rs, objective, stateJson, savedAt, savedBy, json
  148. If Not Api_Authenticate() Then Exit Sub
  149. If Not Api_IsId(id) Then
  150. Api_NotFound
  151. Exit Sub
  152. End If
  153. If Not LoadSession(id, nsId, status, curRev) Then Exit Sub
  154. If Not Api_CanAccessNamespace(nsId, "read") Then
  155. Api_NotFound
  156. Exit Sub
  157. End If
  158. Set rs = DAL().Query("SELECT objective FROM sessions WHERE id = ?", id)
  159. objective = ""
  160. If Not rs.EOF Then objective = "" & rs(0)
  161. rs.Close
  162. stateJson = "null"
  163. savedAt = "null"
  164. savedBy = "null"
  165. If curRev > 0 Then
  166. Set rs = DAL().Query("SELECT state, created_at, created_by FROM checkpoints WHERE session_id = ? AND revision = ?", Array(id, curRev))
  167. If Not rs.EOF Then
  168. stateJson = "" & rs(0)
  169. savedAt = JsonLite_Quote("" & rs(1))
  170. savedBy = JsonLite_Quote("" & rs(2))
  171. End If
  172. rs.Close
  173. End If
  174. Response.AddHeader "ETag", """" & curRev & """"
  175. json = "{""session_id"":" & JsonLite_Quote(id) & ",""status"":" & JsonLite_Quote(status) & ",""objective"":" & JsonLite_Quote(objective) & _
  176. ",""revision"":" & curRev & ",""state"":" & stateJson & ",""saved_at"":" & savedAt & ",""saved_by"":" & savedBy & "}"
  177. Api_Send 200, json
  178. End Sub
  179. '---------------------------------------------------------------
  180. ' POST /api/v1/sessions/:id/complete
  181. '---------------------------------------------------------------
  182. Public Sub Complete(id)
  183. Dim nsId, status, curRev, outcome, body, input, ts, k
  184. If Not Api_Authenticate() Then Exit Sub
  185. If Not Api_IsId(id) Then
  186. Api_NotFound
  187. Exit Sub
  188. End If
  189. If Not LoadSession(id, nsId, status, curRev) Then Exit Sub
  190. If Not Api_CanAccessNamespace(nsId, "write") Then
  191. Api_NotFound
  192. Exit Sub
  193. End If
  194. If status <> "active" Then
  195. Api_Error 409, "session_closed", "The session is already " & status & "."
  196. Exit Sub
  197. End If
  198. outcome = Null
  199. If Request.TotalBytes > 0 Then
  200. body = Api_ReadBody()
  201. If IsEmpty(body) Then Exit Sub
  202. Set input = JsonLite_Parse(body)
  203. If input.Exists("outcome") Then
  204. If Not IsNull(input.Item("outcome")) Then
  205. If VarType(input.Item("outcome")) <> vbString Or Len(input.Item("outcome")) > 4000 Then
  206. Api_Invalid Array("outcome must be a string of at most 4000 characters.")
  207. Exit Sub
  208. End If
  209. outcome = input.Item("outcome")
  210. End If
  211. End If
  212. End If
  213. ts = Api_Now()
  214. On Error Resume Next
  215. DAL().Execute "UPDATE sessions SET status = 'completed', outcome = ?, completed_at = ?, updated_at = ? WHERE id = ? AND tenant_id = ?", _
  216. Array(outcome, ts, ts, id, Api_TenantId)
  217. If Err.Number <> 0 Then
  218. k = Err.Number : Api_NoteDbError
  219. Api_DbFailed k, ""
  220. Exit Sub
  221. End If
  222. On Error GoTo 0
  223. Api_Audit "session.complete", "session", id, "ok"
  224. Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""status"":""completed"",""completed_at"":" & JsonLite_Quote(ts) & "}"
  225. End Sub
  226. '===============================================================
  227. ' Helpers
  228. '===============================================================
  229. ' Loads a session of the caller's tenant. Sends 404 and returns False when absent. Closes its result sets before returning.
  230. Private Function LoadSession(id, ByRef nsId, ByRef status, ByRef curRev)
  231. Dim rs
  232. LoadSession = False
  233. Set rs = DAL().Query("SELECT namespace_id, status FROM sessions WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  234. If rs.EOF Then
  235. rs.Close
  236. Api_NotFound
  237. Exit Function
  238. End If
  239. nsId = "" & rs(0)
  240. status = "" & rs(1)
  241. rs.Close
  242. curRev = 0
  243. Set rs = DAL().Query("SELECT MAX(revision) FROM checkpoints WHERE session_id = ?", id)
  244. If Not rs.EOF Then
  245. If Not IsNull(rs(0)) Then curRev = CLng(rs(0))
  246. End If
  247. rs.Close
  248. LoadSession = True
  249. End Function
  250. ' Required non-empty string; appends to errs (Chr(30)-separated) when invalid
  251. Private Function StringField(input, name, maxLen, ByRef errs)
  252. Dim v, msg
  253. StringField = ""
  254. msg = ""
  255. If Not input.Exists(name) Then
  256. msg = name & " is required."
  257. Else
  258. v = input.Item(name)
  259. If IsNull(v) Then
  260. msg = name & " is required."
  261. ElseIf VarType(v) <> vbString Then
  262. msg = name & " must be a string."
  263. ElseIf Len(Trim(v)) = 0 Then
  264. msg = name & " must not be empty."
  265. ElseIf Len(v) > maxLen Then
  266. msg = name & " must be at most " & maxLen & " characters."
  267. Else
  268. StringField = Trim(v)
  269. End If
  270. End If
  271. If Len(msg) > 0 Then
  272. If Len(errs) > 0 Then errs = errs & Chr(30)
  273. errs = errs & msg
  274. End If
  275. End Function
  276. ' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls and shared call sites)
  277. Public Sub Invoke(actionName, args)
  278. Select Case LCase(actionName)
  279. Case "start" : Start
  280. Case "savestate" : SaveState args(0)
  281. Case "restorestate" : RestoreState args(0)
  282. Case "complete" : Complete args(0)
  283. Case Else
  284. Err.Raise 438, "ApiSessionsController_Class", "Action '" & actionName & "' not found"
  285. End Select
  286. End Sub
  287. End Class
  288. Dim ApiSessionsController_Class__Singleton
  289. Function ApiSessionsController()
  290. If IsEmpty(ApiSessionsController_Class__Singleton) Then
  291. Set ApiSessionsController_Class__Singleton = New ApiSessionsController_Class
  292. End If
  293. Set ApiSessionsController = ApiSessionsController_Class__Singleton
  294. End Function
  295. ' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller)
  296. Sub ApiSessionsController_Invoke(actionName, args)
  297. ApiSessionsController().Invoke actionName, args
  298. End Sub
  299. %>

Powered by TurnKey Linux.