sessions.go
Overview
sessions.go defines the SessionsAPIController, a REST API controller responsible for managing user-agent interaction sessions within the system. It provides HTTP handlers to create, retrieve, list, and delete sessions via JSON-based REST endpoints. The controller acts as an intermediary between HTTP requests and the underlying session service, handling request validation, decoding/encoding JSON payloads, invoking session operations, and formatting HTTP responses.
This file is part of the REST API Controllers set and specifically addresses session lifecycle management in the broader REST API and Web Launchers module. It links external clients with internal session persistence and event handling, enabling session state initialization, event appending, querying, and removal.
Types and Structures
SessionsAPIController
type SessionsAPIController struct {
service session.Service
}
Purpose: Encapsulates session management HTTP handlers.
Fields:
service: Interface to the session service backend that implements session creation, retrieval, updating, and deletion operations.
Functions and Methods
NewSessionsAPIController
func NewSessionsAPIController(service session.Service) *SessionsAPIController
Description: Constructor function to instantiate a new
SessionsAPIController.Parameters:
service(session.Service): The session service implementation to delegate session operations.
Returns: Pointer to a new
SessionsAPIControllerinstance.Usage Example:
sessService := session.NewServiceImplementation(...)
controller := NewSessionsAPIController(sessService)
CreateSessionHandler
func (c *SessionsAPIController) CreateSessionHandler(rw http.ResponseWriter, req *http.Request)
Description: HTTP handler for creating a new session.
Behavior:
Extracts
sessionIDfrom HTTP path parameters viamodels.SessionIDFromHTTPParameters.Decodes optional JSON body into
models.CreateSessionRequest, which may contain initial session state and events.Calls internal
createSessionmethod to create the session and append events.On success, writes the created session as JSON with HTTP 200 OK.
On errors (bad parameters, JSON decode failure, service errors), writes appropriate HTTP error responses.
Parameters:
rw(http.ResponseWriter): Response writer to send HTTP responses.req(*http.Request): Incoming HTTP request.
Returns: None (writes directly to
rw).Usage: Registered as a POST endpoint handler for session creation routes.
createSession (unexported helper)
func (c *SessionsAPIController) createSession(ctx context.Context, sessionID models.SessionID, createSessionRequest models.CreateSessionRequest) (models.Session, error)
Description: Internal helper that invokes the session service to create a session and append events.
Parameters:
ctx(context.Context): Request-scoped context for cancellation and deadlines.sessionID(models.SessionID): Parsed session identifier containing app name, user ID, and session ID.createSessionRequest(models.CreateSessionRequest): Contains initial session state and events.
Returns:
models.Session: The created session model.error: Any error encountered during creation or event appending.
Implementation Details:
Calls
service.Createto create a new session with the given state.Iterates over each event in
createSessionRequest.Events, appending them to the session viaservice.AppendEvent.Converts internal session representation to API model using
models.FromSession.
Error Handling: Returns immediately on any error during creation or event appending.
DeleteSessionHandler
func (c *SessionsAPIController) DeleteSessionHandler(rw http.ResponseWriter, req *http.Request)
Description: HTTP handler to delete a specific session.
Behavior:
Extracts and validates
sessionIDfrom URL parameters.Ensures
sessionID.IDis not empty; returns HTTP 400 if missing.Calls
service.Deletewith the session details.On success, returns HTTP 200 OK with empty JSON response.
On errors, returns HTTP 500 Internal Server Error or HTTP 400 for bad request.
Parameters:
rw(http.ResponseWriter): HTTP response writer.req(*http.Request): HTTP request.
Usage: Registered as a DELETE endpoint for session deletion.
GetSessionHandler
func (c *SessionsAPIController) GetSessionHandler(rw http.ResponseWriter, req *http.Request)
Description: HTTP handler to retrieve a specific session by ID.
Behavior:
Parses
sessionIDfrom URL parameters.Validates presence of
sessionID.ID.Calls
service.Getto fetch the session.Converts internal session representation to API model.
Writes JSON response containing the session.
Handles errors with appropriate HTTP status codes.
Parameters:
rw(http.ResponseWriter): HTTP response writer.req(*http.Request): HTTP request.
Usage: Registered as a GET endpoint for session retrieval.
ListSessionsHandler
func (c *SessionsAPIController) ListSessionsHandler(rw http.ResponseWriter, req *http.Request)
Description: HTTP handler to list all sessions for a given app and user.
Behavior:
Extracts
appNameanduserIDfrom URL parameters usingSessionIDFromHTTPParameters.Calls
service.Listto retrieve all sessions for the user and app.Converts each internal session to API model.
Returns JSON array of sessions with HTTP 200 OK.
Handles errors with HTTP 400 or 500 as appropriate.
Parameters:
rw(http.ResponseWriter): HTTP response writer.req(*http.Request): HTTP request.
Usage: Registered as a GET endpoint for session listing.
Important Implementation Details
SessionID Parsing: All handlers rely on
models.SessionIDFromHTTPParametersto extract session identifiers from HTTP route parameters. This is critical for validating and identifying the session context.JSON Encoding/Decoding: Uses
encoding/jsonfor marshaling and unmarshaling request and response payloads. TheCreateSessionHandlercarefully handles empty request bodies (content length 0).Error Handling: Uniform approach to handle errors by writing HTTP error responses with appropriate status codes and error messages.
Session Service Delegation: The controller delegates all business logic to the injected
session.Serviceinterface, enabling pluggable session backend implementations such as in-memory or database-backed session stores.Event Appending: When creating sessions, the controller appends initial events to the session sequentially to reconstruct session history.
Context Propagation: Contexts from HTTP requests are propagated down to service calls to allow cancellation and tracing.
Interaction with Other Components
Session Service (
session.Service): Core dependency providing methods for creating, deleting, retrieving, listing sessions, and appending events. Implemented elsewhere as per Session Management.Models Package (
models): Provides data structures and conversion functions for session IDs, session representations, and request payloads. Converts between internal and API-facing session formats.HTTP Router (
mux): Usesmux.Vars(req)to extract URL parameters for session identification, integrated in the broader Router Setup.JSON Encoding Utility: Uses
EncodeJSONResponsehelper (not defined in this file but part of the REST API infrastructure) to write JSON responses.Context: Propagates
context.Contextfrom HTTP requests into service calls for lifecycle management.
Workflow Diagrams
SessionsAPIController Structure and Handlers
classDiagram
class SessionsAPIController {
-service: session.Service
+CreateSessionHandler()
+createSession()
+DeleteSessionHandler()
+GetSessionHandler()
+ListSessionsHandler()
}
SessionsAPIController Request Handling Flow
flowchart TD
subgraph Session API Controller
CS[CreateSessionHandler]
CSHelper[createSession]
DS[DeleteSessionHandler]
GS[GetSessionHandler]
LS[ListSessionsHandler]
end
Client_Create --> CS
CS --> CSHelper
CSHelper --> SessionService_Create[session.Service.Create]
CSHelper --> SessionService_AppendEvent[session.Service.AppendEvent]
Client_Delete --> DS
DS --> SessionService_Delete[session.Service.Delete]
Client_Get --> GS
GS --> SessionService_Get[session.Service.Get]
Client_List --> LS
LS --> SessionService_List[session.Service.List]
CSHelper --> EncodeResponse
DS --> EncodeResponse
GS --> EncodeResponse
LS --> EncodeResponse
Usage Examples
Creating a Session (HTTP POST)
Request:
POST /api/apps/{appName}/users/{userID}/sessions/{sessionID}
Content-Type: application/json
{
"state": { ... }, // optional initial state
"events": [ ... ] // optional initial event history
}
Server Processing:
Parses path parameters into
SessionID.Decodes JSON body into
CreateSessionRequest.Invokes
createSessionmethod.Creates session and appends events.
Responds with JSON representation of the created session.
Response:
HTTP/1.1 200 OK
Content-Type: application/json
{
"appName": "...",
"userID": "...",
"sessionID": "...",
"state": { ... },
"events": [ ... ]
}
Retrieving a Session (HTTP GET)
Request:
GET /api/apps/{appName}/users/{userID}/sessions/{sessionID}
Response:
HTTP/1.1 200 OK
Content-Type: application/json
{
"appName": "...",
"userID": "...",
"sessionID": "...",
"state": { ... },
"events": [ ... ]
}
Listing Sessions for a User (HTTP GET)
Request:
GET /api/apps/{appName}/users/{userID}/sessions
Response:
HTTP/1.1 200 OK
Content-Type: application/json
[
{ "appName": "...", "userID": "...", "sessionID": "...", "state": {...}, "events": [...] },
{ "appName": "...", "userID": "...", "sessionID": "...", "state": {...}, "events": [...] }
]
References to Related Topics
REST API and Web Launchers: For the overall REST API server architecture, routing, and integration with web frontends.
Session Management: For details on session lifecycle, state persistence, and storage backends.
Router Setup: For the HTTP routing configuration that exposes these handlers.
REST API Controllers: For the broader context of REST controllers managing runtime, sessions, artifacts, and debugging.
Agent Execution Runner: While not directly invoked here, sessions are foundational to agent runs managed by the runtime controller.
This documentation provides a detailed understanding of the sessions.go file, its role in managing session lifecycle through REST APIs, and its integration within the system's session and agent frameworks.