saveContainerState

open suspend override fun saveContainerState(userId: String, state: KarlContainerState)

Persists a KarlContainerState for the specified user to the database.

This method performs an atomic upsert operation (INSERT OR REPLACE) to store the user's current container state. The state data is serialized as a BLOB and stored with version information for conflict resolution.

Operation Details:

  • SQL Operation: INSERT OR REPLACE for atomic upsert behavior

  • Data Serialization: State data stored as binary BLOB

  • Versioning: Version number stored for optimistic concurrency control

  • Timestamping: updated_at automatically set to current timestamp

Database Transaction:

INSERT OR REPLACE INTO container_states (user_id, state_data, version, updated_at)
VALUES (?, ?, ?, strftime('%s', 'now'))

Threading & Performance:

  • Executes on Dispatchers.IO for non-blocking database access

  • Uses prepared statements for SQL injection prevention

  • Automatic resource cleanup with statement closure

Error Handling:

  • SQLException: Database operation failures with detailed logging

  • Exceptions are re-thrown to calling context for handling

  • Comprehensive error messages include user ID and version information

Concurrency Considerations:

  • UPSERT operation is atomic at the database level

  • Version number can be used for optimistic locking in multi-user scenarios

  • Thread-safe through coroutine context switching to IO dispatcher

Parameters

userId

Unique identifier for the user whose state is being saved. Must be non-null and should be consistent across sessions.

state

The KarlContainerState instance to persist. Contains both the serialized data and version information for storage.

See also

The state data structure being persisted

Corresponding state retrieval operation

Dispatchers.IO

Coroutine context for database operations

Throws

If the database operation fails due to connection issues, constraint violations, or other database-related errors.