NAC_Blockchain/ops/nac-admin/server/mongodb.ts

84 lines
2.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* NAC知识引擎 MongoDB连接模块
*
* 安全说明MongoDB连接串通过 secrets.ts 模块读取,绝不硬编码
*/
import { MongoClient, Db, IndexDirection } from "mongodb";
import { getNacMongoUrl } from "./secrets";
let client: MongoClient | null = null;
let db: Db | null = null;
export async function getMongoDb(): Promise<Db | null> {
if (db) return db;
try {
client = new MongoClient(getNacMongoUrl(), {
serverSelectionTimeoutMS: 5000,
connectTimeoutMS: 5000,
});
await client.connect();
db = client.db("nac_knowledge_engine");
console.log("[MongoDB] Connected to nac_knowledge_engine");
return db;
} catch (error) {
// 只记录错误类型,不记录连接串(含密码)
console.error("[MongoDB] Connection failed:", (error as Error).message);
return null;
}
}
export async function closeMongoDb() {
if (client) {
await client.close();
client = null;
db = null;
}
}
// 集合名称常量
export const COLLECTIONS = {
COMPLIANCE_RULES: "compliance_rules",
CRAWLERS: "crawlers",
CRAWLER_LOGS: "crawler_logs",
APPROVAL_CASES: "approval_cases",
TAG_RULES: "tag_rules",
PROTOCOL_REGISTRY: "protocol_registry",
AUDIT_LOGS: "audit_logs",
KNOWLEDGE_STATS: "knowledge_stats",
// AI智能体对话历史
AGENT_CONVERSATIONS: "agent_conversations",
AGENT_MESSAGES: "agent_messages",
// v15: 规则版本历史
RULE_VERSIONS: "compliance_rule_versions",
};
/**
* 初始化MongoDB索引首次连接时调用
* - agent_conversations: userId + updatedAt 索引(按用户查询最近会话)
* - agent_messages: conversationId + createdAt 索引(按会话查询消息)
* - compliance_rules: 全文检索索引RAG检索增强
*/
export async function ensureIndexes(database: Db): Promise<void> {
try {
// 对话会话索引
await database.collection(COLLECTIONS.AGENT_CONVERSATIONS).createIndex(
{ userId: 1, updatedAt: -1 },
{ background: true }
);
// 对话消息索引
await database.collection(COLLECTIONS.AGENT_MESSAGES).createIndex(
{ conversationId: 1, createdAt: 1 },
{ background: true }
);
// 知识库全文检索索引RAG
await database.collection(COLLECTIONS.COMPLIANCE_RULES).createIndex(
{ ruleName: "text", description: "text", content: "text" },
{ background: true, default_language: "none" } // none = 支持中文分词
);
console.log("[MongoDB] Indexes ensured");
} catch (e) {
// 索引已存在时忽略错误
console.warn("[MongoDB] Index creation warning:", (e as Error).message);
}
}