Skip to content

Services API 文档

概述

Services 是 HeurAMS 的基础设施服务模块,提供通用的基础设施服务,包括配置管理、时间服务、哈希工具等。

核心服务

1. Config - 配置管理

ConfigFile 类

统一的配置管理服务,支持多种配置格式和上下文感知。

python
class ConfigFile:

构造函数:

python
def __init__(self, path: Path, default_config: dict = None)

核心方法:

  • load() - 从文件加载配置
  • save() - 保存配置到文件
  • get(key, default=None) - 获取配置值
  • set(key, value) - 设置配置值
  • update(config_dict) - 批量更新配置

配置格式支持:

  • JSON (.json)
  • TOML (.toml)
  • YAML (.yaml)

使用示例:

python
from heurams.services.config import ConfigFile
from pathlib import Path

# 创建配置管理器
config = ConfigFile(Path("config.toml"))

# 加载配置
config.load()

# 获取配置值
theme = config.get("interface.theme", "dark")

# 设置配置值
config.set("algorithm.default", "supermemo2")

# 保存配置
config.save()

2. Timer - 时间服务

时间戳管理

提供统一的时间戳服务,支持可重写的时间戳机制。

核心函数:

  • get_timestamp() - 获取当前时间戳
  • format_timestamp(timestamp) - 格式化时间戳
  • parse_timestamp(timestamp_str) - 解析时间戳字符串

时间戳格式:

  • Unix 时间戳 (秒级精度)
  • ISO 8601 格式
  • 可读的日期时间格式

使用示例:

python
import heurams.services.timer as timer

# 获取当前时间戳
current_time = timer.get_timestamp()

# 格式化时间戳
formatted = timer.format_timestamp(current_time)

# 解析时间戳字符串
parsed = timer.parse_timestamp("2024-01-01T00:00:00")

时间间隔计算

提供时间间隔计算和日期操作功能。

核心函数:

  • add_days(timestamp, days) - 添加天数
  • diff_days(timestamp1, timestamp2) - 计算天数差
  • is_expired(timestamp) - 检查是否过期

使用示例:

python
from heurams.services.timer import add_days, diff_days

# 计算未来日期
future_date = add_days(current_time, 7)

# 计算日期差
days_passed = diff_days(start_date, end_date)

# 检查是否过期
if is_expired(review_date):
    schedule_review()

3. Hasher - 哈希工具

数据哈希

提供数据哈希和校验功能。

核心函数:

  • hash_data(data) - 计算数据哈希值
  • hash_file(file_path) - 计算文件哈希值
  • verify_hash(data, expected_hash) - 验证数据哈希

支持的哈希算法:

  • MD5
  • SHA-1
  • SHA-256
  • SHA-512

使用示例:

python
import heurams.services.hasher as hasher

# 计算数据哈希
data_hash = hasher.hash_data("hello world")

# 计算文件哈希
file_hash = hasher.hash_file("content.toml")

# 验证哈希
if hasher.verify_hash(data, expected_hash):
    print("数据完整性验证通过")

4. Cache - 缓存服务

内存缓存

提供内存缓存服务,支持过期时间和大小限制。

python
class MemoryCache:

核心方法:

  • get(key) - 获取缓存值
  • set(key, value, ttl=None) - 设置缓存值
  • delete(key) - 删除缓存项
  • clear() - 清空缓存
  • size() - 获取缓存大小

缓存配置:

  • TTL (Time To Live): 缓存过期时间
  • 最大大小: 缓存最大容量限制
  • 淘汰策略: LRU (最近最少使用)

使用示例:

python
from heurams.services.cache import MemoryCache

# 创建缓存实例
cache = MemoryCache(max_size=1000)

# 设置缓存 (1小时过期)
cache.set("user_preferences", preferences, ttl=3600)

# 获取缓存
prefs = cache.get("user_preferences")

# 删除缓存
cache.delete("user_preferences")

5. Logger - 日志服务

日志管理

提供统一的日志记录服务。

核心功能:

  • 多级别日志记录
  • 日志文件轮转
  • 结构化日志格式
  • 上下文信息记录

日志级别:

  • DEBUG
  • INFO
  • WARNING
  • ERROR
  • CRITICAL

使用示例:

python
import heurams.services.logger as logger

# 配置日志
logger.setup(
    level="INFO",
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    file_path="heurams.log"
)

# 记录日志
logger.info("记忆单元加载完成", extra={"unit_id": "001"})
logger.error("算法初始化失败", exc_info=True)

上下文感知服务

ConfigContext 类

上下文感知的配置管理,支持配置继承和覆盖。

python
class ConfigContext:

核心方法:

  • __init__(parent=None) - 创建配置上下文
  • get(key) - 获取配置值 (支持继承)
  • set_local(key, value) - 设置本地配置
  • set_global(key, value) - 设置全局配置

使用示例:

python
from heurams.services.config import ConfigContext

# 创建全局配置上下文
global_config = ConfigContext()
global_config.set_global("theme", "dark")

# 创建本地配置上下文 (继承全局)
local_config = ConfigContext(parent=global_config)
local_config.set_local("font_size", 14)

# 获取配置 (优先使用本地配置)
theme = local_config.get("theme")  # 返回 "dark"
font_size = local_config.get("font_size")  # 返回 14

服务生命周期

服务初始化

python
# 服务初始化示例
from heurams.services import init_services

# 初始化所有服务
services = init_services({
    "config": {"path": "config.toml"},
    "cache": {"max_size": 1000},
    "logger": {"level": "INFO"}
})

服务清理

python
# 服务清理示例
from heurams.services import cleanup_services

# 清理所有服务资源
cleanup_services()

错误处理

配置错误

  • 文件不存在: 使用默认配置并创建文件
  • 格式错误: 提供详细的错误信息和恢复建议
  • 权限错误: 提示用户检查文件权限

服务异常

  • 服务不可用: 降级到备用方案
  • 资源耗尽: 清理资源并重试
  • 超时错误: 提供重试机制

性能优化

缓存策略

  • 配置缓存: 减少文件读取次数
  • 哈希缓存: 避免重复计算
  • 时间缓存: 优化时间戳计算

资源管理

  • 连接池: 重用服务连接
  • 内存优化: 及时释放大对象
  • 文件描述符: 管理文件句柄生命周期

使用示例

完整的服务配置

python
from heurams.services.config import ConfigFile
from heurams.services.cache import MemoryCache
import heurams.services.timer as timer

# 初始化配置
config = ConfigFile("heurams.toml")
config.load()

# 初始化缓存
cache = MemoryCache(max_size=config.get("cache.size", 500))

# 使用时间服务
current_time = timer.get_timestamp()

# 设置缓存
cache.set("last_sync", current_time, ttl=3600)

错误处理示例

python
try:
    config.load()
except FileNotFoundError:
    # 使用默认配置
    config.update(default_config)
    config.save()
except PermissionError:
    logger.error("没有权限读取配置文件")
    raise

扩展接口

自定义服务

开发者可以创建自定义服务:

python
from heurams.services.base import BaseService

class CustomService(BaseService):
    def __init__(self, config):
        super().__init__(config)

    def start(self):
        # 服务启动逻辑
        pass

    def stop(self):
        # 服务停止逻辑
        pass

服务注册

注册自定义服务:

python
from heurams.services.registry import ServiceRegistry

# 注册服务
ServiceRegistry.register("custom", CustomService)

# 获取服务实例
custom_service = ServiceRegistry.get("custom")

兼容性说明

  • Python 版本: 需要 Python 3.8 或更高版本
  • 平台支持: 跨平台支持 (Linux, macOS, Windows)
  • 依赖项: 标准库 + toml (配置解析)
  • 性能要求: 轻量级设计,低资源消耗