storage_session.go
Overview
The storage_session.go file defines the database schema representations and conversion utilities for persisting session and event data in a relational database using GORM ORM. It is part of the Database Session Service which implements the durable storage backend for session management within the system.
This file contains Go struct definitions mapping to the sessions, events, app_states, and user_states tables, with primary keys, foreign key relations, and JSON serialization of complex fields. It also provides helper functions to convert between internal application-level session and event models and their corresponding database storage representations.
By encapsulating the storage models and conversion logic, this file enables consistent and transactional persistence of session state and event histories, facilitating multi-turn user-agent interactions with durable state and event tracking.
Structs and Their Usage
storageSession
Represents a row in the sessions table.
Fields:
AppName(string): Primary key, application namespace.UserID(string): Primary key, identifies the user owning the session.ID(string): Primary key, unique session identifier.State(stateMap): Serialized session-level state map.CreateTime(time.Time): Timestamp of session creation.UpdateTime(time.Time): Timestamp of last update.Events([]storageEvent): One-to-many relation to events belonging to the session.
Methods:
TableName() string: Returns "sessions" to explicitly bind the struct to the database table.
Usage:
Used internally by GORM to persist and query session data.
Holds session metadata and state.
Related events can be eagerly loaded via GORM associations.
storageEvent
Represents a row in the events table.
Fields:
Composite primary key of
ID,AppName,UserID, andSessionID.Metadata fields like
InvocationID,Author,Timestamp.Actions([]byte): JSON marshaled byte slice of event actions.LongRunningToolIDsJSON(dynamicJSON): JSON-encoded list of tool IDs.Optional pointer fields:
Branch,Partial,TurnComplete,ErrorCode,ErrorMessage,Interrupted.JSON-encoded content fields:
Content,GroundingMetadata,CustomMetadata,UsageMetadata,CitationMetadata.Session(storageSession): Belongs-to relationship associating the event with its session.
Methods:
TableName() string: Returns "events" for GORM binding.
Usage:
Stores event-specific data including LLM response metadata and execution details.
JSON marshaling/unmarshaling of complex nested structures is handled externally in conversion functions.
Supports nullable and complex fields with pointers and dynamic JSON.
storageAppState
Represents a row in the app_states table for storing application-scoped state.
Fields:
AppName(string): Primary key.State(stateMap): JSON-serialized state map.UpdateTime(time.Time): Timestamp of last update.
Methods:
TableName() string: Returns "app_states".
Usage:
Stores global state shared across all users and sessions within an application.
Used for merging into session state on retrieval.
storageUserState
Represents a row in the user_states table for storing user-scoped state.
Fields:
Composite primary key:
AppNameandUserID.State(stateMap): JSON-serialized user-specific state.UpdateTime(time.Time): Timestamp of last update.
Methods:
TableName() string: Returns "user_states".
Usage:
Stores state scoped specifically to a user within an application.
Merged with app and session states on retrieval.
Functions and Methods
createStorageSession(s *localSession) (*storageSession, error)
Converts an internal
localSessionobject to astorageSessionfor database persistence.Sets
CreateTimeandUpdateTimeto current time.Returns the constructed
storageSession.
Parameters:
s: Pointer to internal session representation.
Returns:
Pointer to
storageSession.Error (always
nilin current implementation).
Usage Example:
storageSess, err := createStorageSession(localSess)
if err != nil {
// handle error
}
createSessionFromStorageSession(storage *storageSession) (*localSession, error)
Converts a
storageSessionfetched from the database back into the internallocalSessionrepresentation.Copies all relevant fields, including the last
UpdateTime.
Parameters:
storage: Pointer to persistentstorageSession.
Returns:
Pointer to internal
localSession.Error (always
nilin current implementation).
createStorageEvent(session session.Session, event *session.Event) (*storageEvent, error)
Converts a high-level
session.Eventlinked to asession.Sessioninto astorageEventfor database storage.Serializes complex fields such as
Actionsand various JSON metadata fields.Handles nil or empty optional fields by setting pointers accordingly.
Returns a fully populated
storageEvent.
Parameters:
session: Interface representing the current session.event: Pointer to the event to be stored.
Returns:
Pointer to
storageEvent.Error if JSON marshaling fails.
Important Implementation Details:
Marshals
Actionsstruct to JSON bytes.Marshals arrays and maps to JSON strings or bytes.
Converts empty strings to nil pointers for optional database fields.
Uses pointer fields for booleans to distinguish between true, false, and unset.
derefOrZero[T any](p *T) T
Generic helper function to safely dereference a pointer or return the zero value of the type if the pointer is nil.
Used during conversion from storage types to internal models to handle nullable database fields gracefully.
Parameters:
p: Pointer to value of any type.
Returns:
Dereferenced value if
pis not nil.Zero value of type
Totherwise.
createEventFromStorageEvent(se *storageEvent) (*session.Event, error)
Converts a
storageEventretrieved from the database back into an application-levelsession.Event.Unmarshals JSON fields such as
Actions,Content, and metadata fields.Uses
derefOrZeroto safely convert nullable pointer fields.Returns a fully assembled
session.Event.
Parameters:
se: Pointer tostorageEvent.
Returns:
Pointer to
session.Event.Error if any JSON unmarshaling fails.
Usage Notes:
Handles optional JSON fields that may be empty.
Converts JSON string fields for long-running tool IDs into Go slices.
Assembles nested LLM response metadata into the embedded
model.LLMResponsestruct.
Implementation Details and Algorithms
Composite Primary Keys: The primary keys for sessions and events use a combination of
AppName,UserID, andSessionID(plus event ID for events) to support multi-tenant and multi-user isolation.JSON Serialization: Complex nested fields such as
Actionsand LLM response metadata are stored as JSON blobs ([]byteordynamicJSON) in the database, enabling flexible schema evolution without extensive relational schema changes.Pointer Fields for Optional Data: Nullable fields in the database are represented as pointers in Go structs to distinguish between null and zero values, especially for strings and booleans.
Has-Many and Belongs-To Relationships: GORM annotations define the relationships:
A
storageSessionhas manystorageEvents.A
storageEventbelongs to astorageSession.
StateMaps: The
stateMaptype is used for storing session and app/user state as JSON-encoded maps, supporting arbitrary key-value state persistence.Error Handling: Conversion functions return wrapped errors if JSON marshaling/unmarshaling fails, ensuring that database transactions can be rolled back appropriately.
Interaction with Other Components
Session Management: This file supports the Session Management topic by defining the persistent storage layer representations of sessions and events.
Database Backend: It serves as the model layer for the database session service implementation, enabling transactional creation, retrieval, and update of session data.
Agent Execution Runner: The persisted events and session states managed here provide the historical context and state for agent executions (Agent Execution Runner).
LLM Integration: The file handles marshaling/unmarshaling of LLM response metadata and content, integrating with the LLM Integration and Agents components.
Artifact Management: Although not directly managing artifacts, events may reference artifacts, thus linking indirectly to Artifact Management.
Visual Diagram: Class Diagram of Main Structs and Relationships
classDiagram
class storageSession {
+string AppName
+string UserID
+string ID
+stateMap State
+time.Time CreateTime
+time.Time UpdateTime
+[]storageEvent Events
+TableName()
}
class storageEvent {
+string ID
+string AppName
+string UserID
+string SessionID
+string InvocationID
+string Author
+[]byte Actions
+dynamicJSON LongRunningToolIDsJSON
+*string Branch
+time.Time Timestamp
+dynamicJSON Content
+dynamicJSON GroundingMetadata
+dynamicJSON CustomMetadata
+dynamicJSON UsageMetadata
+dynamicJSON CitationMetadata
+*bool Partial
+*bool TurnComplete
+*string ErrorCode
+*string ErrorMessage
+*bool Interrupted
+TableName()
}
class storageAppState {
+string AppName
+stateMap State
+time.Time UpdateTime
+TableName()
}
class storageUserState {
+string AppName
+string UserID
+stateMap State
+time.Time UpdateTime
+TableName()
}
storageSession "1" -- "many" storageEvent : has many
storageEvent "many" -- "1" storageSession : belongs to
Summary of Key Points
Defines storage-layer ORM models for sessions, events, and app/user states with composite keys.
Provides conversion helpers to translate between internal session/event structs and database storage structs.
Handles JSON serialization of complex nested fields and nullable pointers for optional data.
Establishes GORM relationships to maintain referential integrity between sessions and events.
Supports the transactional and consistent persistence needs of the Database Session Service.
Serves as a foundation for durable session state and event history management critical to multi-turn conversational agents.
For detailed usage, lifecycle, and transactional workflows involving these models, see the Database Session Service and Session Management topics.