<% ' ApiSessionsController: agent sessions and working-state checkpoints (spec FR-012, AC-09, AC-10). ' Stateless JSON API, no layout. Helpers (auth, errors, idempotency) are in core/lib.Api.asp. ' ' POST /api/v1/sessions Start {"namespace_id","objective"} -> 201 {"id","status","revision":0} ' PUT /api/v1/sessions/:id/state SaveState {"state":{...}} with If-Match: (0 = none yet) ' GET /api/v1/sessions/:id/state RestoreState latest checkpoint (revision 0 / state null when none) ' POST /api/v1/sessions/:id/complete Complete {"outcome":"..."} optional ' ' Permissions on the session's namespace: write (Start/SaveState/Complete), read (RestoreState). Any principal with ' access to the namespace may resume the session. Stale revisions get 412 and never overwrite a newer checkpoint. Class ApiSessionsController_Class Public Property Get useLayout() useLayout = False End Property Public Property Let useLayout(v) End Property Public Property Get Title() Title = "Sessions API" End Property '--------------------------------------------------------------- ' POST /api/v1/sessions '--------------------------------------------------------------- Public Sub Start() Dim body, input, nsId, objective, idemKey, reqHash, id, ts, resp, k, errs 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(body) If Not Api_IdempotencyGate(idemKey, reqHash) Then Exit Sub errs = "" nsId = StringField(input, "namespace_id", 64, errs) objective = StringField(input, "objective", 2000, errs) If Len(errs) > 0 Then Api_Invalid Split(errs, Chr(30)) Exit Sub End If If Not Api_CanAccessNamespace(nsId, "write") Then Api_Error 404, "namespace_not_found", "Namespace not found." Exit Sub End If id = Api_NewId() ts = Api_Now() resp = "{""id"":" & JsonLite_Quote(id) & ",""status"":""active"",""revision"":0}" On Error Resume Next DAL().BeginTransaction DAL().Execute "INSERT INTO sessions (id, tenant_id, namespace_id, principal_id, objective, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 'active', ?, ?)", _ Array(id, Api_TenantId, nsId, Api_PrincipalId, objective, ts, ts) 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 On Error GoTo 0 Api_Audit "session.start", "session", id, "ok" Response.AddHeader "Location", "/api/v1/sessions/" & id Api_Send 201, resp End Sub '--------------------------------------------------------------- ' PUT /api/v1/sessions/:id/state '--------------------------------------------------------------- Public Sub SaveState(id) Dim body, input, nsId, status, curRev, ifMatch, expected, rs, stateRaw, ts, newRev, k, resp If Not Api_Authenticate() Then Exit Sub If Not Api_IsId(id) Then Api_NotFound Exit Sub End If body = Api_ReadBody() If IsEmpty(body) Then Exit Sub Set input = JsonLite_Parse(body) If Not LoadSession(id, nsId, status, curRev) Then Exit Sub If Not Api_CanAccessNamespace(nsId, "write") Then Api_NotFound Exit Sub End If If status <> "active" Then Api_Error 409, "session_closed", "The session is " & status & "; its state can no longer change." Exit Sub End If If Not input.HasRaw("state") Then Api_Invalid Array("state is required and must be a JSON object.") Exit Sub End If stateRaw = input.Raw("state") If Left(stateRaw, 1) <> "{" Then Api_Invalid Array("state must be a JSON object.") Exit Sub End If If Len(stateRaw) > 65536 Then Api_Invalid Array("state must be at most 64 KB.") Exit Sub End If ifMatch = Replace(Replace(Api_Header("If-Match"), """", ""), "W/", "") expected = ifMatch If Len(expected) = 0 And input.Exists("expected_revision") Then expected = "" & input.Item("expected_revision") If Len(expected) = 0 Then Api_Error 428, "precondition_required", "Send If-Match: (0 when there is none), or ""expected_revision"" in the body." Exit Sub End If If Not IsNumeric(expected) Then Api_Error 400, "invalid_revision", "If-Match / expected_revision must be a revision number." Exit Sub End If If CLng(expected) <> curRev Then Response.AddHeader "ETag", """" & curRev & """" Api_Error 412, "stale_revision", "The session state is at revision " & curRev & ", not " & CLng(expected) & ". Restore it again before saving." Exit Sub End If newRev = curRev + 1 ts = Api_Now() On Error Resume Next ' UNIQUE (session_id, revision) rejects a concurrent writer that passed the check above DAL().Execute "INSERT INTO checkpoints (id, session_id, revision, state, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?)", _ Array(Api_NewId(), id, newRev, stateRaw, Api_PrincipalId, ts) If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Err.Clear On Error GoTo 0 If InStr(LCase(Api_LastDbError), "unique") > 0 Then Api_Error 412, "stale_revision", "Another checkpoint was saved first. Restore the state again before saving." Else Api_DbFailed k, "" End If Exit Sub End If DAL().Execute "UPDATE sessions SET updated_at = ? WHERE id = ?", Array(ts, id) On Error GoTo 0 Api_Audit "session.save_state", "session", id, "ok" Response.AddHeader "ETag", """" & newRev & """" resp = "{""session_id"":" & JsonLite_Quote(id) & ",""revision"":" & newRev & ",""saved_at"":" & JsonLite_Quote(ts) & "}" Api_Send 200, resp End Sub '--------------------------------------------------------------- ' GET /api/v1/sessions/:id/state '--------------------------------------------------------------- Public Sub RestoreState(id) Dim nsId, status, curRev, rs, objective, stateJson, savedAt, savedBy, json If Not Api_Authenticate() Then Exit Sub If Not Api_IsId(id) Then Api_NotFound Exit Sub End If If Not LoadSession(id, nsId, status, curRev) Then Exit Sub If Not Api_CanAccessNamespace(nsId, "read") Then Api_NotFound Exit Sub End If Set rs = DAL().Query("SELECT objective FROM sessions WHERE id = ?", id) objective = "" If Not rs.EOF Then objective = "" & rs(0) rs.Close stateJson = "null" savedAt = "null" savedBy = "null" If curRev > 0 Then Set rs = DAL().Query("SELECT state, created_at, created_by FROM checkpoints WHERE session_id = ? AND revision = ?", Array(id, curRev)) If Not rs.EOF Then stateJson = "" & rs(0) savedAt = JsonLite_Quote("" & rs(1)) savedBy = JsonLite_Quote("" & rs(2)) End If rs.Close End If Response.AddHeader "ETag", """" & curRev & """" json = "{""session_id"":" & JsonLite_Quote(id) & ",""status"":" & JsonLite_Quote(status) & ",""objective"":" & JsonLite_Quote(objective) & _ ",""revision"":" & curRev & ",""state"":" & stateJson & ",""saved_at"":" & savedAt & ",""saved_by"":" & savedBy & "}" Api_Send 200, json End Sub '--------------------------------------------------------------- ' POST /api/v1/sessions/:id/complete '--------------------------------------------------------------- Public Sub Complete(id) Dim nsId, status, curRev, outcome, body, input, ts, k If Not Api_Authenticate() Then Exit Sub If Not Api_IsId(id) Then Api_NotFound Exit Sub End If If Not LoadSession(id, nsId, status, curRev) Then Exit Sub If Not Api_CanAccessNamespace(nsId, "write") Then Api_NotFound Exit Sub End If If status <> "active" Then Api_Error 409, "session_closed", "The session is already " & status & "." Exit Sub End If outcome = Null If Request.TotalBytes > 0 Then body = Api_ReadBody() If IsEmpty(body) Then Exit Sub Set input = JsonLite_Parse(body) If input.Exists("outcome") Then If Not IsNull(input.Item("outcome")) Then If VarType(input.Item("outcome")) <> vbString Or Len(input.Item("outcome")) > 4000 Then Api_Invalid Array("outcome must be a string of at most 4000 characters.") Exit Sub End If outcome = input.Item("outcome") End If End If End If ts = Api_Now() On Error Resume Next DAL().Execute "UPDATE sessions SET status = 'completed', outcome = ?, completed_at = ?, updated_at = ? WHERE id = ? AND tenant_id = ?", _ Array(outcome, ts, ts, id, Api_TenantId) If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Api_DbFailed k, "" Exit Sub End If On Error GoTo 0 Api_Audit "session.complete", "session", id, "ok" Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""status"":""completed"",""completed_at"":" & JsonLite_Quote(ts) & "}" End Sub '=============================================================== ' Helpers '=============================================================== ' Loads a session of the caller's tenant. Sends 404 and returns False when absent. Closes its result sets before returning. Private Function LoadSession(id, ByRef nsId, ByRef status, ByRef curRev) Dim rs LoadSession = False Set rs = DAL().Query("SELECT namespace_id, status FROM sessions WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) If rs.EOF Then rs.Close Api_NotFound Exit Function End If nsId = "" & rs(0) status = "" & rs(1) rs.Close curRev = 0 Set rs = DAL().Query("SELECT MAX(revision) FROM checkpoints WHERE session_id = ?", id) If Not rs.EOF Then If Not IsNull(rs(0)) Then curRev = CLng(rs(0)) End If rs.Close LoadSession = True End Function ' Required non-empty string; appends to errs (Chr(30)-separated) when invalid Private Function StringField(input, name, maxLen, ByRef errs) Dim v, msg StringField = "" msg = "" If Not input.Exists(name) Then msg = name & " is required." Else v = input.Item(name) If IsNull(v) Then msg = name & " is required." ElseIf VarType(v) <> vbString Then msg = name & " must be a string." ElseIf Len(Trim(v)) = 0 Then msg = name & " must not be empty." ElseIf Len(v) > maxLen Then msg = name & " must be at most " & maxLen & " characters." Else StringField = Trim(v) End If End If If Len(msg) > 0 Then If Len(errs) > 0 Then errs = errs & Chr(30) errs = errs & msg End If 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 "start" : Start Case "savestate" : SaveState args(0) Case "restorestate" : RestoreState args(0) Case "complete" : Complete args(0) Case Else Err.Raise 438, "ApiSessionsController_Class", "Action '" & actionName & "' not found" End Select End Sub End Class Dim ApiSessionsController_Class__Singleton Function ApiSessionsController() If IsEmpty(ApiSessionsController_Class__Singleton) Then Set ApiSessionsController_Class__Singleton = New ApiSessionsController_Class End If Set ApiSessionsController = ApiSessionsController_Class__Singleton End Function ' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller) Sub ApiSessionsController_Invoke(actionName, args) ApiSessionsController().Invoke actionName, args End Sub %>