DatomsDBS 技术文档
版本: 1.0
日期: 2024年12月28日
适用于: DatomsDBS v0.1.0+
目录 (Table of Contents)
1. 引言 (Introduction)
1.1. 关于 DatomsDBS
DatomsDBS (DatomsDB Server) 是一个现代化的数据资产管理平台,基于 datomsdb v0.2.3 构建。它为企业和组织提供了一个统一的数据管理解决方案,集成了先进的 AI 技术和强大的数据处理能力。
核心价值
- 统一数据资产管理: 将分散在不同系统中的数据资产统一管理,提供一致的访问接口
- AI 增强查询: 集成自然语言处理能力,用户可以使用自然语言查询数据
- 多源数据连接: 支持 MySQL、PostgreSQL、MongoDB、文件系统等多种数据源
- 完整权限控制: 基于角色的访问控制 (RBAC) 系统,确保数据安全
- 分布式存储: 基于 Hypercore 的分布式存储和版本控制
DatomsDB 核心特性
- EAV 模型: Entity-Attribute-Value 数据模型,提供灵活的数据结构
- Datalog 查询: 强大的声明式查询语言
- 历史追溯: 完整的数据变更历史记录
- 事务处理: ACID 事务保证数据一致性
- 时间维度: 支持时间旅行查询
目标用户
- 数据工程师: 需要管理和处理大量数据源的专业人员
- 数据分析师: 需要快速访问和分析数据的业务用户
- 系统管理员: 负责部署和维护数据基础设施的技术人员
- 开发人员: 需要集成数据服务的应用开发者
1.2. 文档目的与受众
本技术文档旨在为以下群体提供全面的指导:
- 开发者: 了解系统架构、API 使用和扩展开发
- 系统管理员: 掌握部署、配置和运维知识
- 最终用户: 学习如何使用系统功能进行数据管理
- 决策者: 理解系统能力和技术选型参考
1.3. 系统架构概览
高层架构
┌─────────────────────────────────────────────────────────────┐
│ DatomsDBS 系统架构 │
├─────────────────────────────────────────────────────────────┤
│ 前端层 │ Admin Console + Browser Client (HTML+CSS+JS) │
├─────────────────────────────────────────────────────────────┤
│ API 层 │ Express Routes + Controllers + Middleware │
├─────────────────────────────────────────────────────────────┤
│ 服务层 │ DataSource │ DataAsset │ Auth │ AI Agent │
├─────────────────────────────────────────────────────────────┤
│ 连接器层 │ MySQL │ PostgreSQL │ MongoDB │ Files │ APIs │
├─────────────────────────────────────────────────────────────┤
│ 数据层 │ DatomsDB Engine + File Storage + Metadata │
└─────────────────────────────────────────────────────────────┘
核心技术栈
- 后端框架: Node.js + Express.js
- 数据库引擎: DatomsDB v0.2.3
- 前端技术: HTML5 + CSS3 + JavaScript (ES6+)
- 容器化: Docker + Docker Compose
- AI 集成: Ollama (本地 LLM 服务)
- 认证: JWT + RBAC
- 日志系统: Winston
- 测试框架: Jest + Supertest
主要组件
- API 服务器 (
src/server.js): 主服务入口,端口 9000 - 数据库引擎 (
src/db/engine.js): DatomsDB 引擎封装 - 连接器系统 (
src/connectors/): 多数据源连接适配器 - AI Agent (
src/agents/): 自然语言查询处理 - 权限管理 (
src/api/controllers/auth*.js): 认证和授权 - 管理界面 (
public/admin/): Web 管理控制台
2. 快速入门 (Quick Start)
2.1. 环境要求 (Prerequisites)
系统要求
- 操作系统: Linux (Ubuntu 22.04+), macOS (10.15+), Windows (WSL2 推荐)
- 内存: 最低 2GB,推荐 4GB+
- 存储: 最低 10GB 可用空间
- 网络: 稳定的互联网连接(用于下载依赖和 AI 模型)
必要软件依赖
-
Node.js & npm
# 安装 Node.js >= 14.0.0
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs
# 验证安装
node --version # 应该 >= v14.0.0
npm --version # 应该 >= 6.0.0 -
Git
# Ubuntu/Debian
sudo apt-get install git
# 验证安装
git --version -
Docker & Docker Compose (可选,推荐)
# 安装 Docker
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
# 安装 Docker Compose
sudo curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
# 验证安装
docker --version
docker-compose --version -
Ollama (AI 功能,可选)
# 安装 Ollama
curl -fsSL https://ollama.ai/install.sh | sh
# 拉取推荐模型
ollama pull qwen2:1.5b
2.2. 获取代码 (Getting the Code)
# 克隆项目
git clone <YOUR_PROJECT_GIT_URL>
cd datomsDBS
# 查看项目结构
ls -la
2.3. 一键安装与部署 (One-Click Setup)
DatomsDBS 提供了自动化安装脚本,可以在几分钟内完成完整的系统部署。
# 运行一键设置脚本
./scripts/setup_datomsdbs.sh
脚本执行过程
- ✅ 系统要求检查: 验证 Node.js, npm, Git 等依赖
- ✅ 环境配置: 自动生成
.env配置文件 - ✅ 依赖安装: 执行
npm install安装项目依赖 - ✅ 数据目录初始化: 创建数据存储目录结构
- ✅ 基础测试: 可选运行单元测试验证安装
- ✅ 启动选择: 提供多种启动模式选择
预期输出示例
==========================================
DatomsDBS 一键设置脚本 v1.0
==========================================
[STEP] 检查系统要求...
[SUCCESS] Node.js 已安装: v18.19.0
[SUCCESS] npm 已安装: 9.2.0
[SUCCESS] Git 已安装: 2.34.1
[STEP] 创建环境配置文件...
[SUCCESS] .env 文件已创建
[STEP] 安装项目依赖...
[SUCCESS] 依赖安装完成
[STEP] 初始化数据目录...
[SUCCESS] 数据目录创建完成
[STEP] 运行基础测试...
[SUCCESS] 所有测试通过
[INFO] 设置完成!请选择启动方式:
1) npm start - 标准启动
2) npm run dev - 开发模式
3) docker-compose - 容器化启动
4) 手动启动
2.4. 手动安装步骤 (Manual Installation Steps)
如果您偏好手动控制安装过程:
步骤 1: 安装依赖
# 安装 Node.js 依赖
npm install
步骤 2: 配置环境
# 复制环境配置模板
cp .env.example .env
# 或创建基础配置
cat > .env << EOF
NODE_ENV=development
PORT=9000
JWT_SECRET=your-secure-jwt-secret-change-in-production
ADMIN_USERNAME=admin
ADMIN_PASSWORD=admin123
LOG_LEVEL=info
DATA_DIR=./data
AUTO_SAVE_INTERVAL=60000
EOF
步骤 3: 初始化数据目录
# 创建数据目录
mkdir -p data/datoms
mkdir -p data/uploads
mkdir -p data/backups
# 初始化配置文件
echo '[]' > data/dataSources.json
echo '[]' > data/db_list.json
echo '{}' > data/db_access.json
2.5. 启动系统 (Starting the System)
方式 1: 标准启动 (推荐)
# 启动服务
npm start
方式 2: 开发模式
# 启动开发服务(带热重载)
npm run dev
方式 3: Docker 容器化启动
# 使用 Docker Compose
docker-compose up -d
# 查看容器状态
docker-compose ps
# 查看日志
docker-compose logs -f
方式 4: 带 AI 功能启动
# 启动完整环境(包含 Ollama)
./scripts/start-with-ollama.sh
2.6. 访问系统 (Accessing the System)
服务验证
# 健康检查
curl http://localhost:9000/api/health
# 预期响应
{
"status": "ok",
"version": "0.1.0",
"timestamp": "2024-12-28T10:00:00.000Z",
"uptime": 125.5
}
Web 界面访问
- 🌐 主服务: http://localhost:9000
- 🛠️ 管理界面: http://localhost:9000/admin
- 📚 API 文档: http://localhost:9000/api/docs (如果启用)
默认登录凭证
- 用户名:
admin - 密码:
admin123
⚠️ 安全提示: 在生产环境中务必修改默认密码!
3. 配置指南 (Configuration Guide)
3.1. 环境变量 (.env file)
DatomsDBS 使用环境变量进行配置。以下是完整的配置说明:
基础配置
# ===========================================
# 🔧 基础服务配置
# ===========================================
NODE_ENV=development # 运行环境: development/production
PORT=9000 # 服务端口号
LOG_LEVEL=info # 日志级别: debug/info/warn/error
安全配置
# ===========================================
# 🔐 安全与认证配置
# ===========================================
JWT_SECRET=your-jwt-secret-here-change-in-production
API_TOKEN=your-api-token-here
ENABLE_AUTH=true # 启用认证: true/false
ADMIN_USERNAME=admin # 管理员用户名
ADMIN_PASSWORD=admin123 # 管理员密码 (生产环境必须修改!)
🔒 安全建议:
- JWT_SECRET 应该是一个强随机字符串 (≥32字符)
- 生产环境中务必修改默认的管理员密码
- 定期轮换 API_TOKEN
数据存储配置
# ===========================================
# 💾 数据存储配置
# ===========================================
DATA_DIR=./data # 数据目录路径
AUTO_SAVE_INTERVAL=60000 # 自动保存间隔(毫秒)
MAX_FILE_SIZE=100MB # 最大上传文件大小
BACKUP_ENABLED=true # 启用自动备份
BACKUP_INTERVAL=3600000 # 备份间隔(毫秒)
AI Agent 配置
# ===========================================
# 🤖 AI Agent 配置 (可选)
# ===========================================
LLM_SERVICE_URL=http://localhost:11434
LLM_MODEL_NAME=qwen2:1.5b
LLM_TIMEOUT=30000 # LLM 请求超时(毫秒)
ENABLE_AI_AGENTS=true # 启用 AI 代理功能
数据库连接配置
# ===========================================
# 🗄️ 外部数据库配置 (用于连接外部数据源)
# ===========================================
# MySQL 示例
MYSQL_HOST=localhost
MYSQL_PORT=3306
MYSQL_USER=root
MYSQL_PASSWORD=password
# PostgreSQL 示例
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_USER=postgres
POSTGRES_PASSWORD=password
# MongoDB 示例
MONGODB_URI=mongodb://root:password@localhost:27017/admin
高级配置
# ===========================================
# ⚡ 性能优化配置
# ===========================================
WORKER_PROCESSES=4 # 工作进程数 (使用PM2时)
MAX_MEMORY_RESTART=1G # 内存重启阈值
COMPRESSION_ENABLED=true # 启用响应压缩
CACHE_ENABLED=true # 启用缓存
CACHE_TTL=300000 # 缓存过期时间(毫秒)
# ===========================================
# 🌐 网络配置
# ===========================================
CORS_ENABLED=true # 启用跨域
TRUSTED_PROXIES=127.0.0.1 # 信任的代理IP
RATE_LIMIT_ENABLED=true # 启用速率限制
RATE_LIMIT_MAX=100 # 每分钟最大请求数
3.2. DatomsDB Schema 配置
DatomsDB 支持灵活的 Schema 定义,用于描述数据结构和约束。
Schema 基础概念
- Entity: 数据实体,类似于传统数据库中的记录
- Attribute: 属性,定义实体的字段
- Value: 值,属性的具体数据
- Transaction: 事务,原子性的数据变更操作
动态 Schema 生成
DatomsDBS 支持动态生成 Schema,基于数据源的结构自动推断:
// 示例:用户表 Schema
const userSchema = {
id: {
type: 'string',
unique: true,
index: true
},
username: {
type: 'string',
required: true,
unique: true
},
email: {
type: 'string',
required: true,
pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/
},
created_at: {
type: 'instant',
default: () => new Date()
},
active: {
type: 'boolean',
default: true
}
};
Schema 文件位置
- 全局 Schema:
src/db/schemas/global.js - 数据源 Schema:
data/schemas/{dataSourceId}.json - 运行时 Schema: 存储在 DatomsDB 实例中
扩展 Schema
添加新的属性类型:
// 在 src/db/engine.js 中扩展
const customSchemaTypes = {
'geo-point': {
validate: (value) => {
return value.lat && value.lng &&
typeof value.lat === 'number' &&
typeof value.lng === 'number';
},
transform: (value) => ({
lat: parseFloat(value.lat),
lng: parseFloat(value.lng)
})
}
};
3.3. Ollama LLM 配置
Ollama 为 DatomsDBS 提供本地 AI 能力,支持自然语言查询和智能数据分析。
安装和配置 Ollama
# 1. 安装 Ollama
curl -fsSL https://ollama.ai/install.sh | sh
# 2. 启动 Ollama 服务
ollama serve
# 3. 拉取推荐模型
ollama pull qwen2:1.5b # 轻量级中文模型 (1.5GB)
ollama pull llama2:7b # 通用英文模型 (3.8GB)
ollama pull codellama:7b # 代码专用模型 (3.8GB)
模型选择指南
| 模型名称 | 大小 | 语言支持 | 推荐用途 | 内存需求 |
|---|---|---|---|---|
| qwen2:1.5b | 1.5GB | 中英文 | 轻量级查询 | 2GB+ |
| llama2:7b | 3.8GB | 英文为主 | 通用任务 | 8GB+ |
| codellama:7b | 3.8GB | 代码 | 代码分析 | 8GB+ |
| llama2:13b | 7.3GB | 英文 | 复杂推理 | 16GB+ |
Ollama 环境配置
# .env 文件中的 Ollama 配置
LLM_SERVICE_URL=http://localhost:11434
LLM_MODEL_NAME=qwen2:1.5b
LLM_TIMEOUT=30000
LLM_MAX_TOKENS=2048
LLM_TEMPERATURE=0.7
# 可选:GPU 加速配置
OLLAMA_GPU_ENABLED=true
CUDA_VISIBLE_DEVICES=0
Docker 环境中的 Ollama
# docker-compose.yml 中的 Ollama 服务
services:
ollama:
image: ollama/ollama:latest
ports:
- "11434:11434"
volumes:
- ollama_data:/root/.ollama
environment:
- OLLAMA_KEEP_ALIVE=24h
restart: unless-stopped
datomsdbs:
build: .
environment:
- LLM_SERVICE_URL=http://ollama:11434
depends_on:
- ollama
验证 Ollama 配置
# 检查 Ollama 服务状态
curl http://localhost:11434/api/tags
# 测试模型推理
curl http://localhost:11434/api/generate \
-H "Content-Type: application/json" \
-d '{
"model": "qwen2:1.5b",
"prompt": "Hello, how are you?",
"stream": false
}'
# 通过 DatomsDBS API 测试
curl http://localhost:9000/api/agents/chat \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN" \
-d '{
"message": "查询所有用户数据",
"database": "user_data"
}'
4. 核心功能与使用 (Core Features and Usage)
4.1. 数据资产管理
数据资产是 DatomsDBS 的核心概念,它将原始数据源转换为可管理、可查询的数据产品。
4.1.1. 数据资产生命周期
数据源 → 提取配置 → 数据提取 → 转换处理 → 数据资产 → 访问控制 → 数据消费
4.1.2. 创建数据资产
通过 Web 界面创建:
- 登录管理界面:http://localhost:9000/admin
- 选择"数据资产"菜单
- 点击"创建新资产"
- 配置数据资产参数:
- 选择数据源
- 定义提取规则
- 设置转换逻辑
- 配置访问权限
通过 API 创建:
curl -X POST http://localhost:9000/api/data-assets \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "用户活跃度分析",
"sourceId": "ds_mysql_users",
"extractConfig": {
"query": "SELECT user_id, login_time, session_duration FROM user_sessions WHERE DATE(login_time) >= CURDATE() - INTERVAL 30 DAY",
"incremental": true,
"updateField": "login_time"
},
"transformations": [
{
"type": "aggregate",
"groupBy": ["user_id"],
"metrics": ["count(*) as login_count", "avg(session_duration) as avg_session"]
}
]
}'
4.1.3. 数据资产类型
- 原始数据集: 直接从数据源提取的未处理数据
- 聚合视图: 经过聚合计算的汇总数据
- 清洗数据: 经过质量检查和清洗的数据
- 实时流: 持续更新的实时数据流
- 多源融合: 来自多个数据源的融合数据
4.2. 数据源连接与管理
DatomsDBS 支持广泛的数据源类型,提供统一的连接和管理接口。
4.2.1. 支持的数据源类型
关系型数据库:
- MySQL
- PostgreSQL
- SQLite
- Oracle (计划支持)
- SQL Server (计划支持)
NoSQL 数据库:
- MongoDB
- Redis (计划支持)
- Elasticsearch (计划支持)
文件数据源:
- CSV 文件
- Excel 文件 (.xlsx, .xls)
- JSON 文件
- Parquet 文件
- PDF 文档
- 图像文件
API 数据源:
- REST API
- GraphQL (计划支持)
- SOAP (计划支持)
云存储:
- AWS S3
- 本地文件系统
- FTP/SFTP (计划支持)
4.2.2. 连接器配置示例
MySQL 连接器:
{
"type": "mysql",
"config": {
"host": "localhost",
"port": 3306,
"database": "production_db",
"username": "readonly_user",
"password": "secure_password",
"ssl": {
"enabled": true,
"ca": "/path/to/ca.pem"
},
"connectionLimit": 10,
"acquireTimeout": 60000,
"timeout": 60000
}
}
MongoDB 连接器:
{
"type": "mongodb",
"config": {
"uri": "mongodb://username:password@cluster.mongodb.net/database?retryWrites=true&w=majority",
"database": "analytics",
"options": {
"useNewUrlParser": true,
"useUnifiedTopology": true,
"maxPoolSize": 10,
"serverSelectionTimeoutMS": 5000
}
}
}
CSV 连接器:
{
"type": "csv",
"config": {
"filePath": "/data/uploads/sales_data.csv",
"delimiter": ",",
"quote": "\"",
"escape": "\\",
"hasHeader": true,
"encoding": "utf-8",
"skipRows": 0,
"maxRows": -1
}
}
4.2.3. 数据源健康监控
DatomsDBS 提供实时的数据源健康监控:
- 连接状态: 实时检查连接可用性
- 响应时间: 监控查询响应时间
- 错误率: 统计连接和查询错误
- 数据质量: 检查数据完整性和一致性
4.3. AI Agent 系统
AI Agent 系统是 DatomsDBS 的创新功能,允许用户使用自然语言与数据进行交互。
4.3.1. Agent 组件架构
用户输入 → chatAgent → 意图识别 → execAgent → 查询生成 → masterAgent → 结果整合 → 用户界面
主要组件:
- chatAgent (
src/agents/chatAgent.js): 处理自然语言输入,理解用户意图 - execAgent (
src/agents/execAgent.js): 执行具体的数据查询和操作 - masterAgent (
src/agents/masterAgent.js): 协调多个 agent,整合结果
4.3.2. 使用 AI Agent
通过 Web 界面:
- 访问管理界面的"AI 助手"功能
- 选择目标数据库
- 输入自然语言查询,例如:
- "显示过去一周的用户注册趋势"
- "找出销售额最高的前10个产品"
- "分析用户的购买行为模式"
通过 API 调用:
curl -X POST http://localhost:9000/api/agents/chat \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"message": "查询过去30天每日活跃用户数",
"database": "user_analytics",
"context": {
"previousQueries": [],
"preferredFormat": "chart"
}
}'
4.3.3. AI Agent 能力
数据查询:
- 自然语言转 SQL/Datalog 查询
- 复杂聚合和统计分析
- 时间序列分析
- 多表关联查询
数据分析:
- 趋势分析
- 异常检测
- 相关性分析
- 预测建模(基础)
结果呈现:
- 表格数据
- 图表可视化配置
- 分析报告生成
- 洞察摘要
4.4. 权限管理 (RBAC)
DatomsDBS 实现了完整的基于角色的访问控制 (RBAC) 系统。
4.4.1. 权限模型
层次结构:
系统级权限
├── 数据源级权限
│ ├── 数据资产级权限
│ └── 操作级权限
└── 功能级权限
核心概念:
- 用户 (User): 系统使用者
- 角色 (Role): 权限的集合
- 权限 (Permission): 具体的操作授权
- 资源 (Resource): 受保护的系统资源
4.4.2. 预定义角色
管理员 (admin):
- 系统管理:用户管理、系统配置
- 数据管理:所有数据源和资产的完整权限
- 权限管理:角色和权限分配
数据分析师 (analyst):
- 数据访问:读取所有公开数据资产
- 数据查询:执行查询和分析
- 资产创建:创建和管理自己的数据资产
数据工程师 (engineer):
- 数据源管理:创建和配置数据源
- 数据处理:设计和执行数据管道
- 系统监控:访问系统健康和性能指标
业务用户 (viewer):
- 数据浏览:访问分配的数据资产
- 报表查看:查看预定义的报表和仪表板
4.4.3. 权限配置示例
创建角色:
curl -X POST http://localhost:9000/api/admin/roles \
-H "Authorization: Bearer ADMIN_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"id": "data_scientist",
"name": "数据科学家",
"description": "数据科学和机器学习专家",
"permissions": [
"data-sources:read",
"data-assets:read",
"data-assets:create",
"data-assets:update",
"datoms:query",
"datoms:transact",
"agents:use",
"files:upload",
"files:read"
]
}'
分配用户角色:
curl -X PUT http://localhost:9000/api/admin/users/john.doe/roles \
-H "Authorization: Bearer ADMIN_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"roles": ["data_scientist", "analyst"]
}'
4.5. 数据查询
DatomsDBS 支持多种查询方式,从简单的键值查找到复杂的 Datalog 查询。
4.5.1. Datalog 查询基础
基本语法:
[:find ?variable
:where [?entity :attribute ?variable]]
查询示例:
; 查找所有用户的邮箱
[:find ?email
:where [?user :user/email ?email]]
; 查找活跃用户
[:find ?username ?last_login
:where
[?user :user/username ?username]
[?user :user/last_login ?last_login]
[?user :user/active true]]
; 复杂关联查询
[:find ?username (count ?order)
:where
[?user :user/username ?username]
[?order :order/user ?user]
[?order :order/status "completed"]]
4.5.2. SQL 兼容层
为了降低学习成本,DatomsDBS 提供 SQL 兼容的查询接口:
-- 简单查询
SELECT username, email FROM users WHERE active = true;
-- 聚合查询
SELECT DATE(created_at) as date, COUNT(*) as registrations
FROM users
WHERE created_at >= '2024-12-01'
GROUP BY DATE(created_at)
ORDER BY date;
-- 关联查询
SELECT u.username, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE o.status = 'completed'
GROUP BY u.username;
4.5.3. 查询优化
索引策略:
- 自动为频繁查询的属性创建索引
- 支持复合索引
- 时间范围查询优化
查询缓存:
- 自动缓存查询结果
- 智能缓存失效
- 可配置缓存策略
4.6. 数据转换服务
数据转换服务负责将来自不同数据源的数据转换为 DatomsDB 格式。
4.6.1. 转换流程
原始数据 → 格式检测 → 类型推断 → 结构转换 → 验证 → DatomsDB 格式
4.6.2. 支持的转换类型
数据类型转换:
- 字符串 ↔ 数字
- 日期时间格式标准化
- 布尔值规范化
- JSON 对象展开/压缩
结构转换:
- 宽表转长表 (Wide to Long)
- 嵌套 JSON 扁平化
- 数组数据处理
- 关系数据去规范化
数据清洗:
- 空值处理
- 重复数据去除
- 异常值检测和处理
- 数据格式标准化
4.6.3. 自定义转换规则
// 自定义转换器示例
const customTransformer = {
name: 'userProfileTransformer',
description: '用户档案数据转换',
rules: [
{
field: 'birth_date',
transform: (value) => {
// 计算年龄
const age = new Date().getFullYear() - new Date(value).getFullYear();
return { birth_date: value, age: age };
}
},
{
field: 'tags',
transform: (value) => {
// 将逗号分隔的标签转换为数组
return value.split(',').map(tag => tag.trim());
}
}
]
};
5. API 参考 (API Reference)
详细的 API 参考文档请查看:API 参考文档
5.1. 快速 API 概览
认证端点:
POST /api/auth/login- 用户登录GET /api/auth/verify- 令牌验证
数据源管理:
GET /api/data-sources- 获取数据源列表POST /api/data-sources- 创建数据源POST /api/data-sources/{id}/test- 测试连接
数据资产管理:
GET /api/data-assets- 获取数据资产列表POST /api/data-assets- 创建数据资产GET /api/data-assets/{id}- 获取资产详情
DatomsDB 操作:
GET /api/datoms/databases- 获取数据库列表POST /api/datoms/databases/{name}/query- 执行查询POST /api/datoms/databases/{name}/transact- 执行事务
AI Agent:
POST /api/agents/chat- 自然语言查询POST /api/agents/execute- 执行特定 Agent
5.2. 认证方式
JWT Token 认证:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
API Key 认证:
X-API-Key: your-api-key-here
6. 开发指南 (Developer Guide)
6.1. 项目结构
DatomsDBS/
├── src/ # 源代码目录
│ ├── server.js # 服务器入口文件
│ ├── api/ # API 层
│ │ ├── routes/ # 路由定义
│ │ │ ├── index.js # 主路由配置
│ │ │ ├── dataSourceRoutes.js
│ │ │ ├── dataAssetRoutes.js
│ │ │ └── datomsdbApiRoutes.js
│ │ ├── controllers/ # 控制器逻辑
│ │ │ ├── authController.js
│ │ │ ├── dataSourceController.js
│ │ │ └── dataAssetController.js
│ │ └── middleware/ # 中间件
│ │ ├── auth.js
│ │ ├── validation.js
│ │ └── errorHandler.js
│ ├── services/ # 业务逻辑层
│ │ ├── dataSourceService.js # 数据源服务 (1175行)
│ │ ├── dataProductService.js # 数据产品服务 (671行)
│ │ ├── datomsDbManagerService.js # DatomsDB 管理
│ │ ├── FileStorageService.js # 文件存储服务
│ │ └── accessControlService.js # 访问控制服务
│ ├── db/ # 数据库引擎层
│ │ ├── engine.js # 核心数据库引擎 (370行)
│ │ ├── persistence.js # 数据持久化
│ │ └── schemas/ # Schema 定义
│ ├── connectors/ # 数据源连接器
│ │ ├── index.js # 连接器注册
│ │ ├── mysql-connector.js # MySQL 连接器
│ │ ├── postgres-connector.js # PostgreSQL 连接器
│ │ ├── mongodb-connector.js # MongoDB 连接器
│ │ ├── csv-connector.js # CSV 文件连接器
│ │ └── s3-connector.js # AWS S3 连接器
│ ├── agents/ # AI Agent 系统
│ │ ├── chatAgent.js # 聊天代理
│ │ ├── execAgent.js # 执行代理
│ │ └── masterAgent.js # 主协调代理
│ ├── utils/ # 工具库
│ │ ├── logger.js # 日志工具
│ │ ├── crypto.js # 加密工具
│ │ ├── validator.js # 数据验证
│ │ └── fileUtils.js # 文件工具
│ └── config/ # 配置文件
│ ├── database.js # 数据库配置
│ ├── auth.js # 认证配置
│ └── constants.js # 常量定义
├── public/ # 静态资源
│ ├── admin/ # 管理界面
│ │ ├── index.html # 主页面 (689行)
│ │ ├── css/ # 样式文件
│ │ └── js/ # JavaScript 文件
│ ├── css/ # 公共样式
│ └── js/ # 公共脚本
├── data/ # 数据存储目录
│ ├── datoms/ # DatomsDB 数据文件
│ ├── uploads/ # 上传文件
│ ├── backups/ # 备份文件
│ ├── dataSources.json # 数据源配置
│ ├── db_list.json # 数据库列表
│ └── db_access.json # 访问控制配置
├── tests/ # 测试套件
│ ├── basic/ # 基础测试
│ ├── integration/ # 集成测试
│ ├── performance/ # 性能测试
│ └── db_source/ # 测试数据库
├── scripts/ # 脚本文件
│ ├── setup_datomsdbs.sh # 一键安装脚本
│ ├── aws_ec2_test_deployment.sh # AWS 部署脚本
│ └── start-with-ollama.sh # 启动脚本(含AI)
├── deployment/ # 部署配置
│ ├── docker-compose.yml # Docker Compose 配置
│ ├── Dockerfile # Docker 镜像配置
│ └── nginx.conf # Nginx 配置
└── docs/ # 项目文档
├── datomsdbs_technical_documentation.md # 主文档
├── api_reference.md # API 参考
└── deployment_guide.md # 部署指南
6.2. 开发环境设置
6.2.1. 本地开发环境
# 1. 克隆项目
git clone <repository-url>
cd datomsDBS
# 2. 安装依赖
npm install
# 3. 启动测试数据库
cd tests/db_source
docker-compose -f docker-compose-test-dbs.yml up -d
cd ../..
# 4. 配置环境变量
cp .env.example .env
# 编辑 .env 文件,设置必要的配置
# 5. 启动开发服务器
npm run dev
6.2.2. 推荐开发工具
- IDE: Visual Studio Code, WebStorm
- Node.js: v18.x 或更高版本
- 数据库工具: MySQL Workbench, pgAdmin, MongoDB Compass
- API 测试: Postman, Insomnia
- 版本控制: Git
- 容器: Docker Desktop
6.3. 编码规范与最佳实践
6.3.1. JavaScript 编码规范
命名约定:
// 变量和函数:小驼峰命名
const userDataService = new UserDataService();
const getUserById = (id) => { /* ... */ };
// 常量:全大写下划线分隔
const MAX_FILE_SIZE = 10 * 1024 * 1024;
const API_ENDPOINTS = { /* ... */ };
// 类:大驼峰命名
class DataSourceManager {
constructor() { /* ... */ }
}
异步操作:
// 优先使用 async/await
async function fetchUserData(userId) {
try {
const user = await userService.getUserById(userId);
return user;
} catch (error) {
logger.error('Failed to fetch user data', { userId, error });
throw error;
}
}
// 避免嵌套的 Promise 链
// ❌ 不推荐
userService.getUserById(userId)
.then(user => {
return orderService.getOrdersByUser(user.id)
.then(orders => {
return { user, orders };
});
});
// ✅ 推荐
async function getUserWithOrders(userId) {
const user = await userService.getUserById(userId);
const orders = await orderService.getOrdersByUser(user.id);
return { user, orders };
}
错误处理:
// 统一的错误处理模式
class ApiError extends Error {
constructor(message, statusCode = 500, code = 'INTERNAL_ERROR') {
super(message);
this.name = 'ApiError';
this.statusCode = statusCode;
this.code = code;
}
}
// 在控制器中使用
async function createDataSource(req, res, next) {
try {
const dataSource = await dataSourceService.create(req.body);
res.status(201).json({ success: true, data: dataSource });
} catch (error) {
if (error.code === 'DUPLICATE_NAME') {
return next(new ApiError('Data source name already exists', 409, 'DUPLICATE_NAME'));
}
next(error);
}
}
6.3.2. 数据库操作最佳实践
事务管理:
// 使用事务确保数据一致性
async function createDataAssetWithMetadata(assetData, metadata) {
const transaction = await db.beginTransaction();
try {
const asset = await db.dataAssets.create(assetData, { transaction });
await db.assetMetadata.create({
...metadata,
assetId: asset.id
}, { transaction });
await transaction.commit();
return asset;
} catch (error) {
await transaction.rollback();
throw error;
}
}
连接池管理:
// 正确管理数据库连接
class DatabaseConnector {
constructor(config) {
this.pool = mysql.createPool({
...config,
connectionLimit: 10,
acquireTimeout: 60000,
timeout: 60000,
reconnect: true
});
}
async query(sql, params) {
const connection = await this.pool.getConnection();
try {
const [rows] = await connection.execute(sql, params);
return rows;
} finally {
connection.release();
}
}
async close() {
await this.pool.end();
}
}
6.4. 如何运行测试 (Running Tests)
6.4.1. 测试类型
单元测试 (Unit Tests):
# 运行所有单元测试
npm test
# 运行特定测试文件
npm test -- --testPathPattern=dataSource
# 监听模式(自动重新运行)
npm run test:watch
# 生成覆盖率报告
npm run test:coverage
集成测试 (Integration Tests):
# 启动测试数据库
cd tests/db_source
docker-compose -f docker-compose-test-dbs.yml up -d
# 运行集成测试
npm run test:integration
# 清理测试环境
docker-compose -f docker-compose-test-dbs.yml down
端到端测试 (E2E Tests):
# 运行完整的端到端测试
npm run test:e2e
# 运行特定的 E2E 测试套件
npm run test:e2e -- --suite=dataSourceManagement
6.4.2. 测试编写指南
单元测试示例:
// tests/unit/services/dataSourceService.test.js
const DataSourceService = require('../../../src/services/dataSourceService');
const mockConnector = require('../../mocks/connector');
describe('DataSourceService', () => {
let service;
beforeEach(() => {
service = new DataSourceService();
});
describe('createDataSource', () => {
it('should create a data source with valid configuration', async () => {
const config = {
name: 'Test MySQL DB',
type: 'mysql',
config: {
host: 'localhost',
port: 3306,
database: 'testdb'
}
};
const result = await service.createDataSource(config);
expect(result).toHaveProperty('id');
expect(result.name).toBe(config.name);
expect(result.type).toBe(config.type);
});
it('should throw error for duplicate name', async () => {
const config = { name: 'Existing DB', type: 'mysql' };
await service.createDataSource(config);
await expect(service.createDataSource(config))
.rejects
.toThrow('Data source name already exists');
});
});
});
集成测试示例:
// tests/integration/api/dataSource.test.js
const request = require('supertest');
const app = require('../../../src/server');
describe('Data Source API Integration Tests', () => {
let authToken;
beforeAll(async () => {
// 获取认证令牌
const loginResponse = await request(app)
.post('/api/auth/login')
.send({ username: 'admin', password: 'admin123' });
authToken = loginResponse.body.token;
});
describe('POST /api/data-sources', () => {
it('should create a new data source', async () => {
const dataSource = {
name: 'Integration Test DB',
type: 'mysql',
config: {
host: 'localhost',
port: 3306,
database: 'testdb'
}
};
const response = await request(app)
.post('/api/data-sources')
.set('Authorization', `Bearer ${authToken}`)
.send(dataSource)
.expect(201);
expect(response.body.success).toBe(true);
expect(response.body.data).toHaveProperty('id');
});
});
});
6.5. 如何贡献 (Contributing)
6.5.1. 贡献流程
-
Fork 项目
# 在 GitHub 上 Fork 项目
git clone https://github.com/YOUR_USERNAME/datomsDBS.git
cd datomsDBS -
创建功能分支
git checkout -b feature/new-connector-type -
进行开发
- 编写代码
- 添加测试
- 更新文档
-
运行测试
npm test
npm run test:integration
npm run lint -
提交更改
git add .
git commit -m "feat: add support for Oracle database connector" -
推送分支
git push origin feature/new-connector-type -
创建 Pull Request
- 在 GitHub 上创建 PR
- 填写详细的描述
- 等待代码审查
6.5.2. 提交信息规范
使用 Conventional Commits 规范:
<type>[optional scope]: <description>
[optional body]
[optional footer(s)]
类型 (type):
feat: 新功能fix: 错误修复docs: 文档更新style: 代码格式修改refactor: 代码重构test: 测试相关chore: 构建过程或辅助工具的变动
示例:
feat(connector): add Oracle database connector support
- Implement OracleConnector class
- Add connection pooling
- Include error handling for Oracle-specific errors
- Update connector registry
Closes #123
6.6. 调试技巧 (Debugging Tips)
6.6.1. 日志调试
启用详细日志:
# 设置日志级别为 debug
export LOG_LEVEL=debug
npm start
使用结构化日志:
const logger = require('../utils/logger');
// 记录结构化信息
logger.info('Data source connection established', {
dataSourceId: 'ds_123',
type: 'mysql',
host: 'localhost',
responseTime: 45
});
// 记录错误信息
logger.error('Database query failed', {
query: 'SELECT * FROM users',
error: error.message,
stack: error.stack
});
6.6.2. 性能调试
查询性能监控:
// 添加查询执行时间监控
async function executeQuery(sql, params) {
const startTime = Date.now();
try {
const result = await db.query(sql, params);
const executionTime = Date.now() - startTime;
logger.info('Query executed', {
sql: sql.substring(0, 100),
executionTime,
rowCount: result.length
});
return result;
} catch (error) {
logger.error('Query failed', {
sql: sql.substring(0, 100),
error: error.message,
executionTime: Date.now() - startTime
});
throw error;
}
}
内存使用监控:
// 监控内存使用情况
setInterval(() => {
const memUsage = process.memoryUsage();
logger.debug('Memory usage', {
rss: Math.round(memUsage.rss / 1024 / 1024) + ' MB',
heapTotal: Math.round(memUsage.heapTotal / 1024 / 1024) + ' MB',
heapUsed: Math.round(memUsage.heapUsed / 1024 / 1024) + ' MB',
external: Math.round(memUsage.external / 1024 / 1024) + ' MB'
});
}, 30000); // 每30秒记录一次
6.6.3. 数据库调试
检查 DatomsDB 状态:
# 检查数据库列表
curl http://localhost:9000/api/datoms/databases
# 检查特定数据库信息
curl http://localhost:9000/api/datoms/databases/user_analytics/info
# 执行简单查询测试
curl -X POST http://localhost:9000/api/datoms/databases/test_db/query \
-H "Content-Type: application/json" \
-d '{"query": "[:find ?e :where [?e :user/username _]]", "limit": 10}'
测试数据源连接:
# 测试特定数据源连接
curl -X POST http://localhost:9000/api/data-sources/ds_123/test \
-H "Authorization: Bearer YOUR_TOKEN"
# 获取数据预览
curl "http://localhost:9000/api/data-sources/ds_123/preview?limit=5" \
-H "Authorization: Bearer YOUR_TOKEN"
7. 部署 (Deployment)
7.1. Docker Compose 部署 (推荐)
Docker Compose 是最简单快捷的部署方式,适合开发、测试和小规模生产环境。
7.1.1. 标准部署
# 1. 克隆项目
git clone <repository-url>
cd datomsDBS
# 2. 配置环境变量
cp .env.example .env
# 编辑 .env 文件,设置必要的配置
# 3. 启动所有服务
docker-compose up -d
# 4. 查看服务状态
docker-compose ps
# 5. 查看日志
docker-compose logs -f datomsdbs
7.1.2. 带 AI 功能的完整部署
# 使用包含 Ollama 的完整配置
./scripts/start-with-ollama.sh
# 或手动启动
docker-compose -f docker-compose.yml -f docker-compose.ollama.yml up -d
7.1.3. 生产环境优化配置
docker-compose.prod.yml:
version: '3.8'
services:
datomsdbs:
build:
context: .
dockerfile: Dockerfile.prod
ports:
- "${PORT:-9000}:9000"
environment:
- NODE_ENV=production
- JWT_SECRET=${JWT_SECRET}
- API_TOKEN=${API_TOKEN}
- LOG_LEVEL=warn
volumes:
- ./data:/app/data
- ./logs:/app/logs
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:9000/api/health"]
interval: 30s
timeout: 10s
retries: 3
nginx:
image: nginx:alpine
ports:
- "80:80"
- "443:443"
volumes:
- ./deployment/nginx.conf:/etc/nginx/nginx.conf
- ./ssl:/etc/nginx/ssl
depends_on:
- datomsdbs
restart: unless-stopped
redis:
image: redis:alpine
ports:
- "6379:6379"
volumes:
- redis_data:/data
restart: unless-stopped
volumes:
redis_data:
启动生产环境:
# 生产环境部署
docker-compose -f docker-compose.yml -f docker-compose.prod.yml up -d
7.1.4. 数据持久化和备份
数据卷配置:
volumes:
- ./data:/app/data # 应用数据
- ./logs:/app/logs # 日志文件
- ./backups:/app/backups # 备份文件
- ./uploads:/app/uploads # 上传文件
自动备份脚本:
#!/bin/bash
# backup.sh - 自动备份脚本
BACKUP_DIR="/app/backups"
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="datomsdbs_backup_${DATE}.tar.gz"
# 创建备份
tar -czf "${BACKUP_DIR}/${BACKUP_FILE}" \
--exclude='./logs/*' \
--exclude='./backups/*' \
./data
# 清理30天前的备份
find "${BACKUP_DIR}" -name "datomsdbs_backup_*.tar.gz" -mtime +30 -delete
echo "Backup completed: ${BACKUP_FILE}"
7.2. AWS EC2 自动化部署
DatomsDBS 提供完全自动化的 AWS 部署解决方案,适合云环境快速部署和测试。
7.2.1. 快速部署
# 一键 AWS 部署
./scripts/aws_ec2_test_deployment.sh
部署过程:
-
基础设施创建 (2-3分钟)
- VPC 和安全组配置
- SSH 密钥对生成
- EC2 实例启动
-
系统初始化 (5-8分钟)
- Ubuntu 22.04 LTS 系统更新
- Docker 和 Docker Compose 安装
- Node.js 环境配置
-
应用部署 (3-5分钟)
- 代码克隆和构建
- 服务启动和验证
- 健康检查
7.2.2. 部署配置
实例规格:
- 类型: t3.xlarge (4 vCPU, 16GB RAM)
- 存储: 200GB GP3 SSD
- 网络: 公网IP + 安全组
- 区域: ap-southeast-1 (可配置)
安全组规则:
入站规则:
- SSH (22): 0.0.0.0/0
- HTTP (80): 0.0.0.0/0
- HTTPS (443): 0.0.0.0/0
- DatomsDBS (9000): 0.0.0.0/0
- Dev Server (3000): 0.0.0.0/0
- Ollama (11434): 0.0.0.0/0
出站规则:
- All traffic: 0.0.0.0/0
7.2.3. 成本控制
预估费用:
- 实例费用: ~$0.1856/小时
- 存储费用: ~$20/月 (按实际使用)
- 数据传输: 标准费率
自动清理:
# 清理所有测试资源
./scripts/aws_ec2_test_deployment.sh
# 选择 "2) 清理资源"
手动清理:
# 终止实例
aws ec2 terminate-instances --instance-ids i-1234567890abcdef0
# 删除安全组
aws ec2 delete-security-group --group-id sg-abcdef123
# 删除密钥对
aws ec2 delete-key-pair --key-name datomsdbs-test-key
7.2.4. 部署后验证
访问地址:
主服务: http://[PUBLIC_IP]:9000
管理界面: http://[PUBLIC_IP]:9000/admin
开发服务: http://[PUBLIC_IP]:3000
AI 服务: http://[PUBLIC_IP]:11434
健康检查:
# 检查服务状态
curl http://[PUBLIC_IP]:9000/api/health
# 检查容器状态
ssh -i datomsdbs-test-key.pem ubuntu@[PUBLIC_IP] 'docker ps'
# 查看日志
ssh -i datomsdbs-test-key.pem ubuntu@[PUBLIC_IP] 'docker-compose logs -f'
7.3. 高级部署选项
7.3.1. Kubernetes 部署 (计划支持)
基础配置:
# k8s/datomsdbs-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: datomsdbs
labels:
app: datomsdbs
spec:
replicas: 3
selector:
matchLabels:
app: datomsdbs
template:
metadata:
labels:
app: datomsdbs
spec:
containers:
- name: datomsdbs
image: datomsdbs:latest
ports:
- containerPort: 9000
env:
- name: NODE_ENV
value: "production"
- name: JWT_SECRET
valueFrom:
secretKeyRef:
name: datomsdbs-secrets
key: jwt-secret
resources:
limits:
memory: "2Gi"
cpu: "1000m"
requests:
memory: "1Gi"
cpu: "500m"
livenessProbe:
httpGet:
path: /api/health
port: 9000
initialDelaySeconds: 60
periodSeconds: 30
readinessProbe:
httpGet:
path: /api/health
port: 9000
initialDelaySeconds: 30
periodSeconds: 10
---
apiVersion: v1
kind: Service
metadata:
name: datomsdbs-service
spec:
selector:
app: datomsdbs
ports:
- protocol: TCP
port: 80
targetPort: 9000
type: LoadBalancer
7.3.2. 负载均衡和高可用
Nginx 负载均衡配置:
upstream datomsdbs_backend {
server datomsdbs1:9000 weight=1 max_fails=3 fail_timeout=30s;
server datomsdbs2:9000 weight=1 max_fails=3 fail_timeout=30s;
server datomsdbs3:9000 weight=1 max_fails=3 fail_timeout=30s;
}
server {
listen 80;
server_name api.datomsdbs.com;
location / {
proxy_pass http://datomsdbs_backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# 健康检查
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503;
proxy_connect_timeout 5s;
proxy_send_timeout 10s;
proxy_read_timeout 10s;
}
location /api/health {
proxy_pass http://datomsdbs_backend;
access_log off;
}
}
7.3.3. 监控和日志
Prometheus 监控配置:
# monitoring/prometheus.yml
global:
scrape_interval: 15s
scrape_configs:
- job_name: 'datomsdbs'
static_configs:
- targets: ['datomsdbs:9000']
metrics_path: /api/metrics
scrape_interval: 5s
- job_name: 'node-exporter'
static_configs:
- targets: ['node-exporter:9100']
日志聚合 (ELK Stack):
# logging/filebeat.yml
filebeat.inputs:
- type: container
paths:
- '/var/lib/docker/containers/*/*.log'
processors:
- add_docker_metadata:
host: "unix:///var/run/docker.sock"
output.elasticsearch:
hosts: ["elasticsearch:9200"]
index: "datomsdbs-logs-%{+yyyy.MM.dd}"
logging.level: info
8. 故障排除 (Troubleshooting)
8.1. 常见问题及解决方案
8.1.1. 启动和连接问题
问题 1: 服务启动失败
症状:
Error: Cannot find module 'datomsdb'
at Function.Module._resolveFilename
解决方案:
# 重新安装依赖
rm -rf node_modules package-lock.json
npm install
# 检查 Node.js 版本
node --version # 确保 >= 14.0.0
# 清理缓存
npm cache clean --force
问题 2: 端口占用
症状:
Error: listen EADDRINUSE: address already in use :::9000
解决方案:
# 查找占用端口的进程
lsof -i :9000
netstat -tulpn | grep 9000
# 终止占用进程
kill -9 <PID>
# 或修改端口
export PORT=9001
npm start
问题 3: Docker 权限问题
症状:
permission denied while trying to connect to Docker daemon socket
解决方案:
# 将用户添加到 docker 组
sudo usermod -aG docker $USER
# 重新登录或刷新组权限
newgrp docker
# 重启 Docker 服务
sudo systemctl restart docker
8.1.2. 数据库连接问题
问题 1: MySQL 连接失败
症状:
Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'root'@'localhost'
解决方案:
# 检查 MySQL 服务状态
sudo systemctl status mysql
# 重置 MySQL 密码
sudo mysql -u root -p
ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';
FLUSH PRIVILEGES;
# 检查用户权限
SHOW GRANTS FOR 'username'@'hostname';
问题 2: MongoDB 连接超时
症状:
MongoServerSelectionError: connection <monitor> to 127.0.0.1:27017 closed
解决方案:
# 检查 MongoDB 服务
sudo systemctl status mongod
# 启动 MongoDB
sudo systemctl start mongod
# 检查网络连接
telnet localhost 27017
# 检查防火墙规则
sudo ufw status
问题 3: DatomsDB 数据损坏
症状:
Error: Unable to load database: Invalid database format
解决方案:
# 备份损坏的数据库
cp -r data/datoms/corrupted_db data/backups/
# 尝试修复
npm run db:repair corrupted_db
# 从备份恢复
npm run db:restore backup_file.tar.gz
# 重新创建数据库(最后手段)
npm run db:recreate corrupted_db
8.1.3. AI Agent 问题
问题 1: Ollama 服务不可用
症状:
Error: connect ECONNREFUSED 127.0.0.1:11434
解决方案:
# 检查 Ollama 服务状态
curl http://localhost:11434/api/tags
# 启动 Ollama 服务
ollama serve
# 检查 Docker 容器中的 Ollama
docker ps | grep ollama
docker logs ollama_container
# 拉取所需模型
ollama pull qwen2:1.5b
问题 2: AI 响应缓慢
症状: AI 查询响应时间超过 30 秒
解决方案:
# 检查系统资源
htop
nvidia-smi # 如果使用 GPU
# 优化模型配置
export LLM_MODEL_NAME=qwen2:1.5b # 使用更小的模型
export LLM_TIMEOUT=60000 # 增加超时时间
# 启用 GPU 加速(如果可用)
export CUDA_VISIBLE_DEVICES=0
8.1.4. 性能问题
问题 1: 内存使用过高
症状:
FATAL ERROR: Ineffective mark-compacts near heap limit
解决方案:
# 增加 Node.js 堆内存限制
export NODE_OPTIONS="--max-old-space-size=4096"
# 启用内存监控
export LOG_LEVEL=debug
# 检查内存泄漏
npm install -g clinic
clinic doctor -- node src/server.js
问题 2: 查询响应慢
症状: 数据库查询响应时间超过 5 秒
解决方案:
# 启用查询分析
export QUERY_ANALYSIS=true
# 检查数据库索引
curl http://localhost:9000/api/datoms/databases/slow_db/indexes
# 添加索引
curl -X POST http://localhost:9000/api/datoms/databases/slow_db/indexes \
-d '{"attribute": "user_id", "type": "btree"}'
# 优化查询
# 避免全表扫描,使用限制条件
8.2. 日志分析
8.2.1. 日志位置
logs/
├── server.log # 主服务日志
├── error.log # 错误日志
├── access.log # API 访问日志
├── query.log # 数据库查询日志
└── agent.log # AI Agent 日志
8.2.2. 常见错误日志
认证错误:
{
"level": "error",
"message": "Authentication failed",
"timestamp": "2024-12-28T16:00:00.000Z",
"userId": "unknown",
"ip": "192.168.1.100",
"userAgent": "Mozilla/5.0...",
"error": "Invalid token"
}
数据库错误:
{
"level": "error",
"message": "Database operation failed",
"timestamp": "2024-12-28T16:00:00.000Z",
"operation": "query",
"database": "user_analytics",
"query": "[:find ?e :where [?e :user/email _]]",
"error": "Syntax error in query",
"executionTime": 1250
}
系统错误:
{
"level": "error",
"message": "System resource exhausted",
"timestamp": "2024-12-28T16:00:00.000Z",
"resource": "memory",
"usage": "95%",
"threshold": "90%",
"action": "restart_required"
}
8.2.3. 日志分析工具
实时日志监控:
# 实时查看所有日志
tail -f logs/*.log
# 过滤错误日志
grep "ERROR" logs/server.log | tail -20
# 查看特定时间段的日志
grep "2024-12-28T16:" logs/server.log
日志分析脚本:
#!/bin/bash
# analyze_logs.sh - 日志分析脚本
LOG_FILE="logs/server.log"
DATE=$(date +%Y-%m-%d)
echo "=== DatomsDBS 日志分析报告 - $DATE ==="
# 错误统计
echo "错误统计:"
grep "ERROR" $LOG_FILE | wc -l
# 最频繁的错误
echo "最频繁的错误:"
grep "ERROR" $LOG_FILE | awk '{print $4}' | sort | uniq -c | sort -nr | head -5
# API 请求统计
echo "API 请求统计:"
grep "API Request" $LOG_FILE | awk '{print $6}' | sort | uniq -c | sort -nr | head -10
# 响应时间分析
echo "平均响应时间:"
grep "executionTime" $LOG_FILE | awk '{print $NF}' | awk '{sum+=$1; count++} END {print sum/count "ms"}'
8.3. 性能优化
8.3.1. 数据库优化
索引优化:
// 为频繁查询的属性添加索引
await db.addIndex({
attribute: 'user_id',
type: 'hash' // 或 'btree'
});
// 复合索引
await db.addIndex({
attributes: ['user_id', 'created_at'],
type: 'btree'
});
查询优化:
// ❌ 低效查询
[:find ?user
:where [?user :user/active true]]
// ✅ 优化查询(添加选择性更高的条件)
[:find ?user
:where
[?user :user/created_at ?date]
[(>= ?date "2024-12-01")]
[?user :user/active true]]
8.3.2. 应用优化
缓存策略:
const Redis = require('redis');
const redis = Redis.createClient();
// 查询结果缓存
async function getCachedQuery(queryHash, query) {
const cached = await redis.get(`query:${queryHash}`);
if (cached) {
return JSON.parse(cached);
}
const result = await db.query(query);
await redis.setex(`query:${queryHash}`, 300, JSON.stringify(result)); // 5分钟缓存
return result;
}
连接池优化:
// 数据库连接池配置
const poolConfig = {
min: 2, // 最小连接数
max: 10, // 最大连接数
acquireTimeoutMillis: 60000,
idleTimeoutMillis: 300000,
createTimeoutMillis: 30000
};
8.4. 安全问题排查
8.4.1. 认证问题
JWT Token 问题:
# 验证 JWT Secret 配置
echo $JWT_SECRET
# 检查 Token 有效性
curl -X GET http://localhost:9000/api/auth/verify \
-H "Authorization: Bearer YOUR_TOKEN"
# 重新生成强密码
openssl rand -base64 64
8.4.2. 权限问题
检查用户权限:
# 获取用户角色
curl http://localhost:9000/api/admin/users/john.doe \
-H "Authorization: Bearer ADMIN_TOKEN"
# 检查角色权限
curl http://localhost:9000/api/admin/roles/analyst \
-H "Authorization: Bearer ADMIN_TOKEN"
8.5. 获取帮助
8.5.1. 社区支持
- GitHub Issues: 报告 Bug 和功能请求
- 文档: 查阅最新的技术文档
- 示例项目: 参考使用案例
8.5.2. 企业支持
- 技术咨询: 架构设计和最佳实践
- 定制开发: 特定需求的功能开发
- 运维支持: 生产环境的监控和维护
9. 附录 (Appendices)
9.1. DatomsDB 核心概念
9.1.1. 基础概念详解
Entity (实体):
- 代表一个数据对象,类似于传统数据库中的一行记录
- 每个实体都有一个唯一的标识符 (Entity ID)
- 实体本身不包含数据,数据通过属性-值对来描述
Attribute (属性):
- 描述实体特征的命名字段
- 具有固定的数据类型 (string, number, boolean, instant, etc.)
- 可以设置索引、唯一性约束等
Value (值):
- 属性的具体数据内容
- 必须符合属性定义的数据类型
- 支持原始类型和复合类型
Transaction (事务):
- 原子性的数据变更操作集合
- 包含添加、更新、删除等操作
- 具有时间戳,支持历史追溯
9.1.2. EAV 模型示例
传统关系模型:
CREATE TABLE users (
id INT PRIMARY KEY,
username VARCHAR(50),
email VARCHAR(100),
created_at TIMESTAMP
);
INSERT INTO users VALUES (1, 'john_doe', 'john@example.com', '2024-12-28');
DatomsDB EAV 模型:
// 事务形式的数据
[
{op: 'add', entity: 1, attribute: 'user/username', value: 'john_doe'},
{op: 'add', entity: 1, attribute: 'user/email', value: 'john@example.com'},
{op: 'add', entity: 1, attribute: 'user/created_at', value: '2024-12-28T10:00:00.000Z'}
]
// 存储形式 (E-A-V-T)
[
[1, 'user/username', 'john_doe', 1001],
[1, 'user/email', 'john@example.com', 1001],
[1, 'user/created_at', '2024-12-28T10:00:00.000Z', 1001]
]
9.1.3. Schema 属性类型
| 类型 | 描述 | 示例值 | 验证规则 |
|---|---|---|---|
string | 字符串 | "Hello World" | 长度限制、正则表达式 |
number | 数字 | 42, 3.14 | 范围限制、精度控制 |
boolean | 布尔值 | true, false | - |
instant | 时间戳 | Date 对象 | 日期范围验证 |
uuid | UUID | "550e8400-e29b-41d4-a716-446655440000" | UUID 格式验证 |
ref | 引用 | 其他实体的 ID | 引用完整性检查 |
bytes | 二进制数据 | Buffer 对象 | 大小限制 |
9.1.4. 索引类型
EAVT (Entity-Attribute-Value-Time):
- 主索引,支持通过实体查找所有属性
- 查询示例:
[?e :user/username _]
AVET (Attribute-Value-Entity-Time):
- 属性值索引,支持通过属性值查找实体
- 查询示例:
[?e :user/email "john@example.com"]
VAET (Value-Attribute-Entity-Time):
- 引用索引,支持反向引用查询
- 查询示例:查找所有引用特定实体的其他实体
AEVT (Attribute-Entity-Value-Time):
- 属性实体索引,支持属性维度的查询
- 查询示例:按属性分组的统计查询
9.2. 词汇表 (Glossary)
API (Application Programming Interface) 应用程序编程接口,系统间交互的规范化接口
Agent 智能代理,能够自主执行特定任务的软件组件
CRUD (Create, Read, Update, Delete) 数据操作的四种基本功能:创建、读取、更新、删除
Datalog 声明式查询语言,用于查询 DatomsDB 数据
EAV (Entity-Attribute-Value) 实体-属性-值数据模型,DatomsDB 的核心数据结构
JWT (JSON Web Token) 基于 JSON 的开放标准认证令牌
LLM (Large Language Model) 大型语言模型,用于自然语言处理的 AI 模型
RBAC (Role-Based Access Control) 基于角色的访问控制,权限管理模式
Schema 数据结构定义,描述数据的组织和约束
Transaction 事务,保证数据一致性的原子操作单元
9.3. 配置参考
9.3.1. 完整环境变量列表
# ===== 基础配置 =====
NODE_ENV=development|production
PORT=9000
LOG_LEVEL=debug|info|warn|error
APP_NAME=DatomsDBS
# ===== 安全配置 =====
JWT_SECRET=your-jwt-secret-here
JWT_EXPIRES_IN=24h
API_TOKEN=your-api-token-here
ENABLE_AUTH=true|false
ADMIN_USERNAME=admin
ADMIN_PASSWORD=admin123
BCRYPT_SALT_ROUNDS=12
# ===== 数据存储 =====
DATA_DIR=./data
AUTO_SAVE_INTERVAL=60000
BACKUP_ENABLED=true|false
BACKUP_INTERVAL=3600000
MAX_FILE_SIZE=100MB
FILE_UPLOAD_DIR=./uploads
# ===== 数据库配置 =====
DB_CONNECTION_TIMEOUT=30000
DB_QUERY_TIMEOUT=60000
DB_POOL_SIZE=10
ENABLE_QUERY_CACHE=true|false
CACHE_TTL=300000
# ===== AI Agent 配置 =====
LLM_SERVICE_URL=http://localhost:11434
LLM_MODEL_NAME=qwen2:1.5b
LLM_TIMEOUT=30000
LLM_MAX_TOKENS=2048
LLM_TEMPERATURE=0.7
ENABLE_AI_AGENTS=true|false
# ===== 性能优化 =====
WORKER_PROCESSES=4
MAX_MEMORY_RESTART=1G
COMPRESSION_ENABLED=true|false
RATE_LIMIT_ENABLED=true|false
RATE_LIMIT_MAX=100
RATE_LIMIT_WINDOW=60000
# ===== 网络配置 =====
CORS_ENABLED=true|false
CORS_ORIGIN=*
TRUSTED_PROXIES=127.0.0.1
SSL_ENABLED=false
SSL_CERT_PATH=/path/to/cert.pem
SSL_KEY_PATH=/path/to/key.pem
# ===== 监控配置 =====
ENABLE_METRICS=true|false
METRICS_PORT=9001
HEALTH_CHECK_INTERVAL=30000
LOG_ROTATION_SIZE=100MB
LOG_RETENTION_DAYS=30
# ===== 外部服务 =====
REDIS_URL=redis://localhost:6379
ELASTICSEARCH_URL=http://localhost:9200
WEBHOOK_URL=https://hooks.example.com/webhook
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=noreply@example.com
SMTP_PASS=password
9.3.2. Docker Compose 完整配置
docker-compose.full.yml:
version: '3.8'
services:
# 主应用服务
datomsdbs:
build:
context: .
dockerfile: Dockerfile
args:
- NODE_ENV=${NODE_ENV:-production}
ports:
- "${PORT:-9000}:9000"
environment:
- NODE_ENV=${NODE_ENV:-production}
- PORT=9000
- JWT_SECRET=${JWT_SECRET}
- API_TOKEN=${API_TOKEN}
- REDIS_URL=redis://redis:6379
- LLM_SERVICE_URL=http://ollama:11434
volumes:
- ./data:/app/data
- ./logs:/app/logs
- ./uploads:/app/uploads
depends_on:
- redis
- ollama
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:9000/api/health"]
interval: 30s
timeout: 10s
retries: 3
nginx:
image: nginx:alpine
ports:
- "80:80"
- "443:443"
volumes:
- ./deployment/nginx.conf:/etc/nginx/nginx.conf:ro
- ./ssl:/etc/nginx/ssl:ro
depends_on:
- datomsdbs
restart: unless-stopped
redis:
image: redis:7-alpine
ports:
- "6379:6379"
volumes:
- redis_data:/data
restart: unless-stopped
command: redis-server --appendonly yes
volumes:
redis_data:
9.4. 未来展望与路线图
9.4.1. 短期目标 (1-3个月)
核心功能增强:
- 实时数据流处理
- 高级数据可视化组件
- 改进的错误处理和恢复机制
- 增强的安全加密功能
性能优化:
- 查询优化引擎
- 自适应缓存策略
- 数据库分片支持
- 内存使用优化
用户体验:
- 改进的 Web 界面
- 移动端适配
- 拖拽式查询构建器
- 实时协作功能
9.4.2. 中期目标 (3-6个月)
架构演进:
- 微服务架构重构
- Kubernetes 原生支持
- 事件驱动架构
- 插件系统开发
数据处理:
- 流式数据处理
- 机器学习集成
- 数据血缘追踪
- 自动化数据治理
集成能力:
- 第三方系统集成
- API 网关集成
- 消息队列支持
- 云原生部署
9.4.3. 长期愿景 (6-12个月)
分布式能力:
- P2P 数据同步
- 多节点集群
- 数据复制和一致性
- 分布式查询优化
AI 增强:
- 自然语言到SQL转换
- 智能数据发现
- 异常检测和预警
- 自动化运维
生态建设:
- 开源社区建设
- 插件市场
- 认证和培训体系
- 商业化支持
9.4.4. 技术趋势适应
新兴技术集成:
- Vector 数据库支持
- 图数据库功能
- 时序数据优化
- 边缘计算支持
标准和协议:
- OpenAPI 3.0 完整支持
- GraphQL 查询接口
- 数据目录标准
- 隐私计算协议
详细的发展路线图请参考:未来改进路线图
结语
DatomsDBS 作为一个现代化的数据资产管理平台,集成了先进的数据库技术、AI 能力和云原生架构。本文档涵盖了从快速入门到高级部署的全方位内容,旨在帮助不同层次的用户充分利用系统的强大功能。
随着项目的不断发展,我们将持续更新和完善这份文档。如果您在使用过程中遇到问题或有改进建议,欢迎通过 GitHub Issues 或其他渠道与我们联系。
感谢您选择 DatomsDBS,期待与您一起构建更好的数据管理生态!
文档版本: 1.0
最后更新: 2024年12月28日
维护者: DatomsDBS 开发团队
许可证: MIT License