Class MysqlAgentStateStore

java.lang.Object
io.agentscope.extensions.mysql.state.MysqlAgentStateStore
All Implemented Interfaces:
io.agentscope.core.state.AgentStateStore

public class MysqlAgentStateStore extends Object implements io.agentscope.core.state.AgentStateStore
MySQL database-based session implementation.

This implementation stores session state in MySQL database tables with the following structure:

  • Single state: stored as JSON with item_index = 0
  • List state: each item stored in a separate row with item_index = 0, 1, 2, ...

Table Schema (auto-created if createIfNotExist=true):

 CREATE TABLE IF NOT EXISTS agentscope_sessions (
     session_id VARCHAR(255) NOT NULL,
     state_key VARCHAR(255) NOT NULL,
     item_index INT NOT NULL DEFAULT 0,
     state_data LONGTEXT NOT NULL,
     created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
     updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
     PRIMARY KEY (session_id, state_key, item_index)
 ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
 

Features:

  • True incremental list storage (only INSERTs new items, no read-modify-write)
  • Type-safe state serialization using Jackson
  • Automatic table creation
  • SQL injection prevention through parameterized queries
  • Constructor Details

    • MysqlAgentStateStore

      public MysqlAgentStateStore(DataSource dataSource)
      Create a MysqlAgentStateStore with default settings.

      This constructor uses default database name (agentscope) and table name ( agentscope_sessions), and does NOT auto-create the database or table. If the database or table does not exist, an IllegalStateException will be thrown.

      Parameters:
      dataSource - DataSource for database connections
      Throws:
      IllegalArgumentException - if dataSource is null
      IllegalStateException - if database or table does not exist
    • MysqlAgentStateStore

      public MysqlAgentStateStore(DataSource dataSource, boolean createIfNotExist)
      Create a MysqlAgentStateStore with optional auto-creation of database and table.

      This constructor uses default database name (agentscope) and table name ( agentscope_sessions). If createIfNotExist is true, the database and table will be created automatically if they don't exist. If false and the database or table doesn't exist, an IllegalStateException will be thrown.

      Parameters:
      dataSource - DataSource for database connections
      createIfNotExist - If true, auto-create database and table; if false, require existing
      Throws:
      IllegalArgumentException - if dataSource is null
      IllegalStateException - if createIfNotExist is false and database/table does not exist
    • MysqlAgentStateStore

      public MysqlAgentStateStore(DataSource dataSource, String databaseName, String tableName, boolean createIfNotExist)
      Create a MysqlAgentStateStore with custom database name, table name, and optional auto-creation.

      If createIfNotExist is true, the database and table will be created automatically if they don't exist. If false and the database or table doesn't exist, an IllegalStateException will be thrown.

      Parameters:
      dataSource - DataSource for database connections
      databaseName - Custom database name (uses default if null or empty)
      tableName - Custom table name (uses default if null or empty)
      createIfNotExist - If true, auto-create database and table; if false, require existing
      Throws:
      IllegalArgumentException - if dataSource is null
      IllegalStateException - if createIfNotExist is false and database/table does not exist
  • Method Details

    • supportsVersioning

      public boolean supportsVersioning()
      Specified by:
      supportsVersioning in interface io.agentscope.core.state.AgentStateStore
    • save

      public void save(String userId, String sessionId, String key, io.agentscope.core.state.State value)
      Specified by:
      save in interface io.agentscope.core.state.AgentStateStore
    • getVersioned

      public <T extends io.agentscope.core.state.State> io.agentscope.core.state.VersionedState<T> getVersioned(String userId, String sessionId, String key, Class<T> type)
      Specified by:
      getVersioned in interface io.agentscope.core.state.AgentStateStore
    • saveIfVersion

      public long saveIfVersion(String userId, String sessionId, String key, io.agentscope.core.state.State value, long expectedVersion)
      Specified by:
      saveIfVersion in interface io.agentscope.core.state.AgentStateStore
    • save

      public void save(String userId, String sessionId, String key, List<? extends io.agentscope.core.state.State> values)
      Save a list of state values with hash-based change detection.

      This method uses hash-based change detection to handle both append-only and mutable lists:

      • If the hash changes (list was modified), all existing items are deleted and rewritten
      • If the list shrinks, all existing items are deleted and rewritten
      • If the list only grows (append-only), only new items are inserted
      • If nothing changes, the operation is skipped
      Specified by:
      save in interface io.agentscope.core.state.AgentStateStore
      Parameters:
      userId - the user identifier
      sessionId - the session identifier
      key - the state key (e.g., "memory_messages")
      values - the list of state values to save
    • get

      public <T extends io.agentscope.core.state.State> Optional<T> get(String userId, String sessionId, String key, Class<T> type)
      Specified by:
      get in interface io.agentscope.core.state.AgentStateStore
    • getList

      public <T extends io.agentscope.core.state.State> List<T> getList(String userId, String sessionId, String key, Class<T> itemType)
      Specified by:
      getList in interface io.agentscope.core.state.AgentStateStore
    • exists

      public boolean exists(String userId, String sessionId)
      Specified by:
      exists in interface io.agentscope.core.state.AgentStateStore
    • delete

      public void delete(String userId, String sessionId)
      Specified by:
      delete in interface io.agentscope.core.state.AgentStateStore
    • listSessionIds

      public Set<String> listSessionIds(String userId)
      Specified by:
      listSessionIds in interface io.agentscope.core.state.AgentStateStore
    • close

      public void close()
      Close the session and release any resources.

      Note: This implementation does not close the DataSource as it may be shared across multiple sessions. The caller is responsible for managing the DataSource lifecycle.

      Specified by:
      close in interface io.agentscope.core.state.AgentStateStore
    • getDatabaseName

      public String getDatabaseName()
      Get the database name used for storing sessions.
      Returns:
      The database name
    • getTableName

      public String getTableName()
      Get the table name used for storing sessions.
      Returns:
      The table name
    • getDataSource

      public DataSource getDataSource()
      Get the DataSource used for database connections.
      Returns:
      The DataSource instance
    • clearAllSessions

      @Deprecated public int clearAllSessions()
      Deprecated.
      Clear all sessions from the database (for testing or cleanup).
      Returns:
      Number of rows deleted
    • truncateAllSessions

      public int truncateAllSessions()
      Truncate session table from the database (for testing or cleanup).

      This method clears all session records by executing a TRUNCATE TABLE statement on the sessions table. TRUNCATE is faster than DELETE as it resets the table without logging individual row deletions and reclaims storage space immediately.

      Note: In MySQL, TRUNCATE TABLE is DDL, triggers an implicit commit, and is not rollbackable. For that reason, this method executes the statement directly instead of routing it through executeInWriteTransaction(Connection, SqlOperation).

      Note: The TRUNCATE operation requires DROP privileges in MySQL.

      Returns:
      typically 0 if successful
    • validateSessionId

      protected void validateSessionId(String sessionId)
      Validate a session ID format.
      Parameters:
      sessionId - AgentStateStore ID to validate
      Throws:
      IllegalArgumentException - if session ID is invalid