using BotSharp.Plugin.MongoStorage.Collections; namespace BotSharp.Plugin.MongoStorage; public class MongoDbContext { private readonly MongoClient _mongoClient; private readonly string _mongoDbDatabaseName; private readonly string _collectionPrefix; public MongoDbContext(BotSharpDatabaseSettings dbSettings) { var mongoDbConnectionString = dbSettings.BotSharpMongoDb; _mongoClient = new MongoClient(mongoDbConnectionString); _mongoDbDatabaseName = GetDatabaseName(mongoDbConnectionString); _collectionPrefix = dbSettings.TablePrefix.IfNullOrEmptyAs("BotSharp"); //CreateIndex(); } private string GetDatabaseName(string mongoDbConnectionString) { var databaseName = mongoDbConnectionString.Substring(mongoDbConnectionString.LastIndexOf("/", StringComparison.InvariantCultureIgnoreCase) + 1); if (databaseName.Contains("?")) { databaseName = databaseName.Substring(0, databaseName.IndexOf("?", StringComparison.InvariantCultureIgnoreCase)); } return databaseName; } private IMongoDatabase Database { get { return _mongoClient.GetDatabase(_mongoDbDatabaseName); } } private IMongoCollection CreateConversationIndex() { var collection = Database.GetCollection($"{_collectionPrefix}_Conversations"); var indexes = collection.Indexes.List().ToList(); var createTimeIndex = indexes.FirstOrDefault(x => x.GetElement("name").ToString().StartsWith("CreatedTime")); if (createTimeIndex == null) { var indexDef = Builders.IndexKeys.Descending(x => x.CreatedTime); collection.Indexes.CreateOne(new CreateIndexModel(indexDef)); } return collection; } private IMongoCollection CreateAgentTaskIndex() { var collection = Database.GetCollection($"{_collectionPrefix}_AgentTasks"); var indexes = collection.Indexes.List().ToList(); var createTimeIndex = indexes.FirstOrDefault(x => x.GetElement("name").ToString().StartsWith("CreatedTime")); if (createTimeIndex == null) { var indexDef = Builders.IndexKeys.Descending(x => x.CreatedTime); collection.Indexes.CreateOne(new CreateIndexModel(indexDef)); } return collection; } public IMongoCollection Agents => Database.GetCollection($"{_collectionPrefix}_Agents"); public IMongoCollection AgentTasks { get { return CreateAgentTaskIndex(); } } public IMongoCollection Conversations { get { return CreateConversationIndex(); } } public IMongoCollection ConversationDialogs => Database.GetCollection($"{_collectionPrefix}_ConversationDialogs"); public IMongoCollection ConversationStates => Database.GetCollection($"{_collectionPrefix}_ConversationStates"); public IMongoCollection ExectionLogs => Database.GetCollection($"{_collectionPrefix}_ExecutionLogs"); public IMongoCollection Users => Database.GetCollection($"{_collectionPrefix}_Users"); public IMongoCollection UserAgents => Database.GetCollection($"{_collectionPrefix}_UserAgents"); public IMongoCollection LlmCompletionLogs => Database.GetCollection($"{_collectionPrefix}_Llm_Completion_Logs"); public IMongoCollection Plugins => Database.GetCollection($"{_collectionPrefix}_Plugins"); }