Metadata-Version: 2.5
Name: ys_base
Version: 0.1.99
Summary: YS 统一 SDK：契约模型 / auth 客户端与差量同步 / 应用服务骨架
Author-email: ys <popsars@gmail.com>
License: MIT
Requires-Python: >=3.13
Requires-Dist: cryptography<50,>=43
Requires-Dist: loguru<1,>=0.7
Requires-Dist: pydantic<3,>=2.7
Requires-Dist: pymongo<5,>=4.17
Requires-Dist: websockets<16,>=13
Provides-Extra: server
Requires-Dist: fastapi<1,>=0.115; extra == 'server'
Requires-Dist: pyjwt[crypto]<3,>=2.9; extra == 'server'
Requires-Dist: uvicorn[standard]<1,>=0.30; extra == 'server'
Requires-Dist: zstandard<1,>=0.23; extra == 'server'
Description-Content-Type: text/markdown

# ys_base

YS 统一 SDK：契约模型（contracts）、auth 客户端与差量同步（auth）、WebSocket RPC 基类（ws）、
Mongo 存储（store，随基础安装）、子系统服务骨架（server，extra）。
交易网关已独立为 `ys_trade_sdk`，网关改动不再升本包。

```bash
pip install ys_base            # 契约 + auth 客户端 + Mongo 存储
pip install ys_base[server]    # + FastAPI 子系统骨架
```

使用 uv 添加依赖：

```bash
uv add ys_base             # 契约 + auth 客户端 + Mongo 存储
uv add "ys_base[server]"   # + FastAPI 子系统骨架
uv add ys_trade_sdk        # 交易网关，独立版本
```

本仓库开发与全量测试需要安装全部 extras：

```bash
uv python install 3.13
uv sync --all-extras --frozen
uv run pytest
```

## 列表搜索（0.1.98 起）

服务端过滤的列表用 `ys_base.search`，规则与前端 `@ysgroup/core` 的 `ysSearchText` / `ysMatch` 完全相同
（全角转半角、不分大小写、空格分隔多关键词全部命中、拼音首字母/全拼/zh ch sh/最后一字半个全拼/多音字、
数字两边去千分位、数字原值自动加两位小数）。拼音数据与前端同源，由 `tools/pinyin/build.py` 生成，无第三方依赖。

```python
from ys_base.search import ys_filter, ys_match, ys_matcher, ys_search_text


def text_of(row: dict) -> str:
    # 传页面上显示的文字（含格式化后的数字），数字字段再传一次原值
    return ys_search_text(row["name"], row["status_label"], f"{row['amount']:,.2f}", row["amount"])


ys_match(text_of(row), "zhs 1,377")  # 单行判断
rows = ys_filter(rows, keyword, text_of)  # 逐行过滤，关键词只处理一次
match = ys_matcher(keyword)  # 或自己循环：match(text) -> bool
```

`Decimal`、`bson.Decimal128` 按数字处理；`bool` 写成 `true`/`false`，`list`/`tuple` 展开，`None`、空串跳过。

## 文件存储（0.1.99 起）

业务文件（附件、凭证、材料）存进本系统 Mongo，用 `ys_base.files` 统一处理分块、压缩、加密、上传会话、断点续传和清理，
业务仓只传配置、写权限。需要 `ys_base[server]`（含 `zstandard`）。

存储格式与 Template `files`、ys_bill `bill_files`、ys_hrms `employee_files` 现有数据一致，不需迁移：

- 元数据集合一行一个文件：`name`、`ext`、`content_type`、`size`（原始字节数）、`stored_size`（落库字节数）、
  `chunk_count`、`checksum`（原文件 sha256）、上传人（`owner_field`，默认 `user_id`）、`status`、创建/更新时间，加业务字段。
- 块集合 `_id` 为「文件ID:序号」：`file_id`、`index`、`size`、`compression`（`zstd` / `none`）、`data`，
  新写入的块另带 `raw_sha256`；配置了 `transform` 时带它的标记字段（如 `encryption`）。
  每块原始 1 MiB，zstd 10 级压缩，省不到 5% 原样存。压缩、解压、加解密、哈希都在线程里做。
- 上传会话记在元数据行上：`status="uploading"`、`received`（已连续收到的块数）、`upload_expires_at`（过期时间，
  默认 24 小时，每收一块或续传顺延）。上传编号就是文件 ID。服务重启不删未完成上传，浏览器可续传；
  过期的由 `cleanup_expired()` 清理（`attach(server)` 在启动时和每小时调用），`cancel` 立即删。
- 块写入幂等：重发已收到的块，内容 sha256 一致直接确认；只接受 `index == received` 的新块。
  `finish` 逐块读回解码，核对每块大小、总大小与 sha256（50 MB 在内存存储上约 0.05 秒，不含 Mongo 读取）。

规则统一：文件名 1～120 字、无控制字符（含路径时只取文件名）；空文件拒绝；序号与 size 严格核对；首块交给
`validate` 查文件头，不符立即丢弃；每人同时上传默认 6 个。错误文案与现有一致：「单个文件不能超过 N MB」
「文件内容不能为空」「上传已失效，请重新上传」「文件块顺序不对，请重新上传」「文件块大小不对，请重新上传」
「文件校验不一致，传输过程中内容有损坏，请重新上传」「文件内容缺失，请联系管理员」等。

```python
FileStore(
    store,  # server.store
    files="files",
    chunks="file_chunks",
    max_size=50 * 1024 * 1024,
    max_uploads_per_user=6,
    upload_ttl_seconds=24 * 3600,
    time_unit="s",  # "s"：秒 float；"ms"：毫秒 int
    owner_field="user_id",
    created_field="created_at",
    updated_field="updated_at",
    ready_status="ready",
    validate=None,  # (name, size, content_type, head: bytes | None) -> str | None，可为 async
    transform=None,  # ChunkTransform：marks、encode(data, file_id, index, compression)、decode(...)
    on_finish=None,  # async (record) -> result | None
    integrity_message="文件内容完整性校验失败",
)
```

方法：`begin(name, size, content_type, *, user_id, extra=None, file_id="")`、`put_chunk(upload_id, user_id, index, data, size)`、
`resume(upload_id, user_id, *, name, size, chunk_count)`、`finish(upload_id, user_id, checksum, *, on_finish=None)`、
`cancel(upload_id, user_id)`、`cleanup_expired()`、`ensure_indexes()`、`attach(server)`、`get(file_id)`、`get_file(file_id)`、
`read_chunk(file_id, index, *, meta=None)`、`read_all(file_id, *, meta=None)`、`write_bytes(name, content, *, content_type, user_id, extra, file_id, on_finish)`、
`delete(file_id)`、`delete_chunks(file_id)`。

`finish` 生效时去掉 `received`、`upload_expires_at`，写入 `checksum`、`stored_size`、`status=ready_status` 后调 `on_finish(record)`；
返回值非 None 作为结果，否则返回元数据；核对失败或 `on_finish` 抛错都删除整个上传。

标准事件 `register_file_events(router, files, *, authorize, prepare=None, on_finish=None, names=FileEventNames())`：
默认事件 `begin_file_upload`、`upload_file_chunk`、`finish_file_upload`、`cancel_file_upload`、`resume_file_upload`、
`read_file_chunk`（只读），`FileEventNames` 里设为 `None` 的不注册。钩子：

- `authorize(ctx, action, record) -> user`：`action` 为 begin/chunk/finish/cancel/resume/read，begin 时 `record` 为 None；
- `prepare(ctx, user, data) -> dict`：begin 时补业务字段；
- `on_finish(ctx, user, record) -> result`：生效后的处理（广播、写业务记录），返回值即 finish 结果。

Template 标准用法：

```python
from ys_base.files import FileStore, register_file_events
from ys_base.server import EventRouter

files = FileStore(server.store)  # files / file_chunks、50 MB


async def authorize(ctx, action, record):
    return await require_user(ctx, "files")


async def prepare(ctx, user, data):
    return {"memo": text(data.get("memo"), "备注"), "deleted_at": None}


async def finished(ctx, user, record):
    await broadcast_change(ctx, "upsert", record["_id"])
    return public_file(record, await users(ctx.server))


server.include_ws_router(
    register_file_events(EventRouter("files"), files, authorize=authorize, prepare=prepare, on_finish=finished)
)
files.attach(server)  # 启动建索引、清过期上传，之后每小时清一次
# 彻底删除：await files.delete(file_id)
```

ys_bill：自定义集合、白名单与 5 MB：

```python
FILE_TYPES = {"application/pdf": (b"%PDF-",), "image/png": (b"\x89PNG\r\n\x1a\n",), "image/jpeg": (b"\xff\xd8\xff",)}


def validate(name, size, content_type, head):
    content_type = {"image/jpg": "image/jpeg"}.get(content_type.lower(), content_type.lower())
    if content_type not in FILE_TYPES:
        raise BusinessError("只能上传 PDF、PNG 或 JPG 文件")
    if head is not None and not head.startswith(FILE_TYPES[content_type]):
        raise BusinessError("文件内容与类型不符")
    return content_type  # begin 时写入规范化后的类型


files = FileStore(
    server.store, files="bill_files", chunks="bill_file_chunks", max_size=5 * 1024 * 1024, validate=validate
)
```

ys_hrms：加密 transform、毫秒时间戳、自定义事件名（多个 begin 事件自己写，通用的发块、续传、完成、取消用标准事件）：

```python
class MaterialCipher:
    marks = {"encryption": "aes-gcm"}

    def __init__(self, server):
        self.server = server

    def encode(self, data, file_id, index, compression):
        nonce = os.urandom(12)
        return nonce + file_cipher(self.server).encrypt(nonce, data, f"{file_id}:{index}:{compression}".encode())

    def decode(self, data, file_id, index, compression):
        return file_cipher(self.server).decrypt(data[:12], data[12:], f"{file_id}:{index}:{compression}".encode())


files = FileStore(
    server.store,
    files="employee_files",
    chunks="employee_file_chunks",
    time_unit="ms",
    owner_field="uploaded_by",
    created_field="uploaded_at",
    validate=lambda name, size, content_type, head: head is not None and check_head(file_extension(name), head),
    transform=MaterialCipher(server),
    integrity_message="材料内容完整性校验失败",
)
# begin_material_upload：plan_upload 拼好记录后 files.begin(record["name"], size, record["content_type"],
#   user_id=operator_id(user), extra=record)；完成回调按记录分派（材料 commit_upload / 制度附件 attach_policy_file）。
register_file_events(
    router,
    files,
    authorize=authorize_by_record,  # 按记录上的业务字段重新校验页面授权
    on_finish=commit_by_record,
    names=FileEventNames(
        begin=None,
        chunk="upload_material_chunk",
        finish="finish_material_upload",
        cancel="cancel_material_upload",
        resume="resume_material_upload",
        read=None,
    ),
)
# 制度附件元数据记在 hr_policies.file：files.read_chunk(file_id, index, meta=policy["file"])
```

`LocalStore` 同时新增 `find_local(table, query)`、`delete_local_where(table, query)`（字段相等条件；MongoStore 走索引，
`delete_local_where` 不接受空条件）。

## 快速发布到 PyPI

先在 `ys_base/__init__.py` 中更新 `__version__`。PyPI 不允许覆盖已经发布的同版本文件，因此每次发布必须使用新版本号。
使用 project-scoped PyPI token，并将其保存在 macOS 钥匙串，不在项目目录、环境文件或 Shell 配置中保存明文 Token。

必须使用经典的“钥匙串访问”应用手动添加:文件 -> 新建密码项，不要使用新版“密码”App。新版“密码”App 管理的是网站密码，会强制要求填写网站，凭据类型不适合 PyPI 发布 Token。

在“钥匙串访问”中选择“登录”钥匙串，手动添加密码项目并填写：

- 钥匙串项目名称：`pypi:__token__`
- 账户名称：当前 macOS 用户名
- 密码：完整的 PyPI project-scoped Token

保存后不要使用会直接输出密码内容的命令检查 Token。发布脚本会从钥匙串读取该通用密码，并只注入单次 `uv publish` 进程，不会打印、写入项目文件或长期导出为环境变量。

在 `ys_platform` 仓库根目录执行：

```bash
cd ys_base
./publish-pypi.sh
```

脚本会自动运行测试、构建、审计 wheel/sdist、上传，并校验 PyPI 文件哈希。发布成功后等清华镜像可下载该版本，再在消费仓升锁：

```bash
uv cache clean ys-base
version=$(sed -n 's/__version__ = "\([^"]*\)"/\1/p' ys_base/ys_base/__init__.py)
# 确认清华镜像已有该版本后再执行
uv add "ys_base==$version"
```

交易客户端、行情、静态信息和收益数据服务在 `ys_trade_sdk`。每个 `TradeManager` 独占一个 `TradeRuntime`。

业务系统使用 `ys_base 0.1.29` 后，Auth 协议逻辑表名继续保持 `users`、`owners`、`accounts`、`brokers`；Mongo 物理镜像统一为 `_auth_*`，同步状态为 `_auth_sync_state`，本地身份集合为 `_local_users`、`_local_user_roles`。MongoStore 启动时只对历史集合执行预检后的原地 rename，检测到新旧集合或同步状态键并存会拒绝启动。

```python
from ys_trade_sdk import (
    Account,
    TradeManager,
    TradeRuntimeConfig,
)

manager = TradeManager(
    accounts=[
        Account(
            account="A001",
            password="...",
            trade_source="xt",
            trade_uri="ws://trade.example.com",
            profit_enabled=True,
        )
    ],
    runtime_config=TradeRuntimeConfig(
        quote_data_base_url="http://quote.example.com",
        symbol_data_base_url="http://symbol.example.com",
        symbol_data_username="symbol-user",
        symbol_data_password="symbol-password",
        trade_data_base_url="http://trade-data.example.com",
        trade_data_username="trade-user",
        trade_data_password="trade-password",
    ),
)

quotes = await manager.query_snapshots({"600000.SH", "300750.SZ"})
refreshed = await manager.query_snapshots_with_refresh({"600000.SH"}, {"f43", "f58", "f60"})
statics = await manager.query_static_infos({"600000.SH"}, {"name", "pre_close"})
alive = await manager.check_snapshot_service_alive()
```

`DefaultSnapshotFields == "f43,f58,f60"`，返回原始 `f*` 字段，并固定映射
`f43 -> close`、`f60 -> pre_close`、`f58 -> name`。不提供 `last_price` 或 `pre_price` 兼容字段；
可通过字符串或字段集合指定其他 `fields`。

- `query_snapshots()` 是无缓存单次查询，不登记后台刷新标的。
- `query_snapshots_with_refresh()` 登记当日标的和字段，并在 `09:00:00-15:30:00` 每 2 秒持续刷新；
  当日标的和字段只增不减。
- Snapshot 和 StaticInfo 缓存在上海自然日变化时会同时清空日期、标的、字段和记录。
- 只有账号 `profit_enabled=True`（Trade 本地字段，缺省为 True）时，才要求 Snapshot、StaticInfo 和 TradeData 三类服务地址齐全。

刚发布的新版本若已在 PyPI 页面可见，但 uv 仍提示该版本不存在，通常是清华镜像尚未同步，或本地缓存的 Simple Index 尚未更新。生产锁文件必须继续走清华镜像，禁止 `--default-index https://pypi.org/simple`。

先确认镜像：

```bash
curl -fsS "https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple/ys-base/" | grep "ys_base-$version"
```

镜像已有该版本后，清理单包缓存再升锁：

```bash
uv cache clean ys-base
uv add "ys_base==$version" --refresh
```

如果仍无法解析，再清理完整缓存后重试同一条 `uv add`，不要改官方源。镜像长时间没有该版本时停止升锁并等待同步。

当前四仓边界、公共包依赖和配置规则见仓库根 `docs/业务系统架构方案.md`；开发与发版见 `docs/业务系统开发规范.md`。
