|
| 1 | +package link.socket.ampere |
| 2 | + |
| 3 | +import app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver |
| 4 | +import kotlinx.coroutines.CoroutineScope |
| 5 | +import kotlinx.coroutines.Dispatchers |
| 6 | +import kotlinx.coroutines.SupervisorJob |
| 7 | +import kotlinx.coroutines.cancel |
| 8 | +import kotlinx.serialization.json.Json |
| 9 | +import link.socket.ampere.agents.events.EnvironmentService |
| 10 | +import link.socket.ampere.agents.events.relay.EventRelayService |
| 11 | +import link.socket.ampere.agents.events.utils.ConsoleEventLogger |
| 12 | +import link.socket.ampere.agents.events.utils.EventLogger |
| 13 | +import link.socket.ampere.data.DEFAULT_JSON |
| 14 | +import link.socket.ampere.db.Database |
| 15 | +import java.io.File |
| 16 | + |
| 17 | +/** |
| 18 | + * Context that provides dependencies for CLI commands. |
| 19 | + * |
| 20 | + * AmpereContext handles all the initialization and wiring of the environment, |
| 21 | + * so commands just receive the services they need without worrying about |
| 22 | + * how they're created. |
| 23 | + * |
| 24 | + * This class: |
| 25 | + * - Initializes the database connection |
| 26 | + * - Creates the database schema |
| 27 | + * - Sets up the coroutine scope for async operations |
| 28 | + * - Creates the EnvironmentService with all orchestrators and repositories |
| 29 | + * - Provides access to services for CLI commands |
| 30 | + * |
| 31 | + * Usage: |
| 32 | + * ```kotlin |
| 33 | + * val context = AmpereContext() |
| 34 | + * context.start() |
| 35 | + * try { |
| 36 | + * // Use context.environmentService or context.eventRelayService |
| 37 | + * } finally { |
| 38 | + * context.close() |
| 39 | + * } |
| 40 | + * ``` |
| 41 | + */ |
| 42 | +class AmpereContext( |
| 43 | + /** |
| 44 | + * Path to the SQLite database file. |
| 45 | + * Defaults to "ampere.db" in the user's home directory. |
| 46 | + */ |
| 47 | + databasePath: String = defaultDatabasePath(), |
| 48 | + |
| 49 | + /** |
| 50 | + * JSON configuration for serialization. |
| 51 | + * Defaults to the standard Ampere JSON configuration. |
| 52 | + */ |
| 53 | + json: Json = DEFAULT_JSON, |
| 54 | + |
| 55 | + /** |
| 56 | + * Event logger for system operations. |
| 57 | + * Defaults to console logging. |
| 58 | + */ |
| 59 | + logger: EventLogger = ConsoleEventLogger(), |
| 60 | +) { |
| 61 | + /** |
| 62 | + * Database driver for SQLite operations. |
| 63 | + */ |
| 64 | + private val driver: JdbcSqliteDriver = createDriver(databasePath) |
| 65 | + |
| 66 | + /** |
| 67 | + * Database instance with all queries. |
| 68 | + */ |
| 69 | + private val database: Database = createDatabase(driver) |
| 70 | + |
| 71 | + /** |
| 72 | + * Coroutine scope for async operations. |
| 73 | + * Uses Dispatchers.Default with a SupervisorJob for fault tolerance. |
| 74 | + */ |
| 75 | + private val scope: CoroutineScope = CoroutineScope(Dispatchers.Default + SupervisorJob()) |
| 76 | + |
| 77 | + /** |
| 78 | + * The environment service that provides access to all repositories, |
| 79 | + * orchestrators, and agent APIs. |
| 80 | + */ |
| 81 | + val environmentService: EnvironmentService = EnvironmentService.create( |
| 82 | + database = database, |
| 83 | + scope = scope, |
| 84 | + json = json, |
| 85 | + logger = logger, |
| 86 | + ) |
| 87 | + |
| 88 | + /** |
| 89 | + * Convenience accessor for the event relay service. |
| 90 | + * This is commonly needed by CLI commands that watch or query events. |
| 91 | + */ |
| 92 | + val eventRelayService: EventRelayService |
| 93 | + get() = environmentService.eventRelayService |
| 94 | + |
| 95 | + /** |
| 96 | + * Start all orchestrator services. |
| 97 | + * |
| 98 | + * This must be called before using the context to ensure event routing |
| 99 | + * and other background operations are active. |
| 100 | + */ |
| 101 | + fun start() { |
| 102 | + environmentService.start() |
| 103 | + } |
| 104 | + |
| 105 | + /** |
| 106 | + * Close all resources and stop background operations. |
| 107 | + * |
| 108 | + * This should be called when the CLI is shutting down to ensure |
| 109 | + * clean resource cleanup. |
| 110 | + */ |
| 111 | + fun close() { |
| 112 | + scope.cancel() |
| 113 | + driver.close() |
| 114 | + } |
| 115 | + |
| 116 | + companion object { |
| 117 | + /** |
| 118 | + * Default database path in the user's home directory. |
| 119 | + */ |
| 120 | + private fun defaultDatabasePath(): String { |
| 121 | + val homeDir = System.getProperty("user.home") |
| 122 | + return File(homeDir, ".ampere/ampere.db").absolutePath |
| 123 | + } |
| 124 | + |
| 125 | + /** |
| 126 | + * Create a JDBC SQLite driver with proper configuration. |
| 127 | + */ |
| 128 | + private fun createDriver(databasePath: String): JdbcSqliteDriver { |
| 129 | + // Ensure parent directory exists |
| 130 | + val dbFile = File(databasePath) |
| 131 | + dbFile.parentFile?.mkdirs() |
| 132 | + |
| 133 | + return JdbcSqliteDriver("jdbc:sqlite:$databasePath") |
| 134 | + } |
| 135 | + |
| 136 | + /** |
| 137 | + * Create the database instance and initialize the schema if needed. |
| 138 | + */ |
| 139 | + private fun createDatabase(driver: JdbcSqliteDriver): Database { |
| 140 | + // Check if the main table exists to determine if we need to create the schema |
| 141 | + val schemaExists = try { |
| 142 | + driver.executeQuery<Boolean>( |
| 143 | + identifier = null, |
| 144 | + sql = "SELECT name FROM sqlite_master WHERE type='table' AND name='EventStore'", |
| 145 | + mapper = { cursor -> |
| 146 | + app.cash.sqldelight.db.QueryResult.Value(cursor.next().value) |
| 147 | + }, |
| 148 | + parameters = 0, |
| 149 | + binders = null |
| 150 | + ).value |
| 151 | + } catch (e: Exception) { |
| 152 | + false |
| 153 | + } |
| 154 | + |
| 155 | + if (!schemaExists) { |
| 156 | + // Schema doesn't exist, create it |
| 157 | + Database.Schema.create(driver) |
| 158 | + } |
| 159 | + |
| 160 | + return Database(driver) |
| 161 | + } |
| 162 | + } |
| 163 | +} |
0 commit comments