ys_base 0.2.2__tar.gz → 0.2.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. {ys_base-0.2.2 → ys_base-0.2.3}/.gitignore +3 -0
  2. {ys_base-0.2.2 → ys_base-0.2.3}/PKG-INFO +7 -1
  3. {ys_base-0.2.2 → ys_base-0.2.3}/README.md +6 -0
  4. {ys_base-0.2.2 → ys_base-0.2.3}/tests/test_app_server.py +5 -1
  5. {ys_base-0.2.2 → ys_base-0.2.3}/tests/test_logging.py +19 -4
  6. ys_base-0.2.3/tests/test_runtime_info.py +25 -0
  7. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/__init__.py +1 -1
  8. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/auth/client.py +4 -0
  9. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/server/app_server.py +7 -0
  10. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/server/logging.py +8 -6
  11. ys_base-0.2.3/ys_base/server/runtime_info.py +61 -0
  12. {ys_base-0.2.2 → ys_base-0.2.3}/.python-version +0 -0
  13. {ys_base-0.2.2 → ys_base-0.2.3}/pyproject.toml +0 -0
  14. {ys_base-0.2.2 → ys_base-0.2.3}/tests/memory_store.py +0 -0
  15. {ys_base-0.2.2 → ys_base-0.2.3}/tests/test_api_token.py +0 -0
  16. {ys_base-0.2.2 → ys_base-0.2.3}/tests/test_contracts.py +0 -0
  17. {ys_base-0.2.2 → ys_base-0.2.3}/tests/test_crypto.py +0 -0
  18. {ys_base-0.2.2 → ys_base-0.2.3}/tests/test_files.py +0 -0
  19. {ys_base-0.2.2 → ys_base-0.2.3}/tests/test_files_migrate.py +0 -0
  20. {ys_base-0.2.2 → ys_base-0.2.3}/tests/test_http_errors.py +0 -0
  21. {ys_base-0.2.2 → ys_base-0.2.3}/tests/test_iso_reference.py +0 -0
  22. {ys_base-0.2.2 → ys_base-0.2.3}/tests/test_mongo_store.py +0 -0
  23. {ys_base-0.2.2 → ys_base-0.2.3}/tests/test_rpc_client.py +0 -0
  24. {ys_base-0.2.2 → ys_base-0.2.3}/tests/test_search.py +0 -0
  25. {ys_base-0.2.2 → ys_base-0.2.3}/tests/test_store_delta.py +0 -0
  26. {ys_base-0.2.2 → ys_base-0.2.3}/uv.lock +0 -0
  27. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/_pinyin_data.py +0 -0
  28. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/auth/__init__.py +0 -0
  29. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/auth/api_token.py +0 -0
  30. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/auth/delta.py +0 -0
  31. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/contracts/__init__.py +0 -0
  32. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/contracts/authorization.py +0 -0
  33. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/contracts/base.py +0 -0
  34. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/contracts/enums.py +0 -0
  35. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/contracts/iso_reference.py +0 -0
  36. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/contracts/master.py +0 -0
  37. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/contracts/platform.py +0 -0
  38. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/contracts/relations.py +0 -0
  39. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/crypto.py +0 -0
  40. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/files.py +0 -0
  41. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/files_migrate.py +0 -0
  42. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/py.typed +0 -0
  43. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/search.py +0 -0
  44. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/server/__init__.py +0 -0
  45. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/server/errors.py +0 -0
  46. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/server/http_errors.py +0 -0
  47. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/server/jwt_verify.py +0 -0
  48. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/server/router.py +0 -0
  49. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/store/__init__.py +0 -0
  50. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/store/base.py +0 -0
  51. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/store/mongo.py +0 -0
  52. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/ws/__init__.py +0 -0
  53. {ys_base-0.2.2 → ys_base-0.2.3}/ys_base/ws/rpc_client.py +0 -0
@@ -22,3 +22,6 @@ ys_base/.pypi_token
22
22
  ys_web/**/dist/
23
23
  smoke_app.log
24
24
  /data/
25
+
26
+ # 生产配置不提交,按 config.example.yaml 复制填写
27
+ /config.yaml
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: ys_base
3
- Version: 0.2.2
3
+ Version: 0.2.3
4
4
  Summary: YS 统一 SDK:契约模型 / auth 客户端与差量同步 / 应用服务骨架
5
5
  Author-email: ys <popsars@gmail.com>
6
6
  License: MIT
@@ -44,6 +44,12 @@ uv sync --all-extras --frozen
44
44
  uv run pytest
45
45
  ```
46
46
 
47
+ ## 进程日志与运行环境上报(0.2.3 起)
48
+
49
+ - `configure_logging()` 写标准错误和 `app/logs/app-YYYY-MM-DD.log`:每天零点(进程所在时区,容器设 `TZ=Asia/Shanghai`)切新文件,保留 30 天。0.2.2 及以前只按 10 MB 滚动,写的是 `app.log`;升级后它不再写入,确认不需要后手动删除。
50
+ - `AppServer` 注册时向 Auth 上报 `runtime`:Python 版本、自家 Python 包(`ys-base`、装了的 `ys-trade-sdk`)版本、`web/package.json` 里 `@ysgroup/*` 的版本、主机名、进程号、启动时间。只报版本,不报路径、环境变量和配置。镜像里要带上 `web/package.json`(Template 的 `deploy/Dockerfile` 已复制),没有时前端版本为空。Auth 在应用管理「运行状态」里展示。
51
+ - 浏览器经业务系统登录(`login`)和兑换跳转码(`exchange_sso_code`)时,`AppServer` 把浏览器连接的对端地址写进转给 Auth 的 `client_ip`(覆盖浏览器自己带的值),Auth 只认已注册应用连接上报的这个字段。
52
+
47
53
  ## 列表搜索(0.1.98 起)
48
54
 
49
55
  服务端过滤的列表用 `ys_base.search`,规则与前端 `@ysgroup/core` 的 `ysSearchText` / `ysMatch` 完全相同
@@ -25,6 +25,12 @@ uv sync --all-extras --frozen
25
25
  uv run pytest
26
26
  ```
27
27
 
28
+ ## 进程日志与运行环境上报(0.2.3 起)
29
+
30
+ - `configure_logging()` 写标准错误和 `app/logs/app-YYYY-MM-DD.log`:每天零点(进程所在时区,容器设 `TZ=Asia/Shanghai`)切新文件,保留 30 天。0.2.2 及以前只按 10 MB 滚动,写的是 `app.log`;升级后它不再写入,确认不需要后手动删除。
31
+ - `AppServer` 注册时向 Auth 上报 `runtime`:Python 版本、自家 Python 包(`ys-base`、装了的 `ys-trade-sdk`)版本、`web/package.json` 里 `@ysgroup/*` 的版本、主机名、进程号、启动时间。只报版本,不报路径、环境变量和配置。镜像里要带上 `web/package.json`(Template 的 `deploy/Dockerfile` 已复制),没有时前端版本为空。Auth 在应用管理「运行状态」里展示。
32
+ - 浏览器经业务系统登录(`login`)和兑换跳转码(`exchange_sso_code`)时,`AppServer` 把浏览器连接的对端地址写进转给 Auth 的 `client_ip`(覆盖浏览器自己带的值),Auth 只认已注册应用连接上报的这个字段。
33
+
28
34
  ## 列表搜索(0.1.98 起)
29
35
 
30
36
  服务端过滤的列表用 `ys_base.search`,规则与前端 `@ysgroup/core` 的 `ysSearchText` / `ysMatch` 完全相同
@@ -300,6 +300,8 @@ async def test_front_login_forwards_server_app_name():
300
300
  return {"user": {"_id": "u1"}, "access_token": "a", "refresh_token": "r"}
301
301
 
302
302
  class FakeWs:
303
+ client = SimpleNamespace(host="10.1.2.3")
304
+
303
305
  async def send_text(self, payload):
304
306
  self.payload = payload
305
307
 
@@ -311,7 +313,8 @@ async def test_front_login_forwards_server_app_name():
311
313
  {
312
314
  "id": "1",
313
315
  "event": "login",
314
- "data": {"username": "u", "password": "p", "app_name": "auth"},
316
+ # 浏览器自带的 client_ip 不可信,由本服务覆盖成真实来源。
317
+ "data": {"username": "u", "password": "p", "app_name": "auth", "client_ip": "9.9.9.9"},
315
318
  },
316
319
  )
317
320
 
@@ -322,6 +325,7 @@ async def test_front_login_forwards_server_app_name():
322
325
  "username": "u",
323
326
  "password": "p",
324
327
  "app_name": "demo",
328
+ "client_ip": "10.1.2.3",
325
329
  },
326
330
  )
327
331
  ]
@@ -1,10 +1,11 @@
1
1
  # -*- coding: utf-8 -*-
2
- """进程日志:落盘 app/logs/app.log,接管 uvicorn 访问日志。"""
2
+ """进程日志:按天落盘 app/logs/app-YYYY-MM-DD.log,接管 uvicorn 访问日志。"""
3
3
 
4
4
  from __future__ import annotations
5
5
 
6
6
  import logging
7
7
  import re
8
+ from datetime import date
8
9
 
9
10
  import pytest
10
11
  from loguru import logger
@@ -14,6 +15,10 @@ from ys_base.server import logging as logmod
14
15
  TIMESTAMP = re.compile(r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}")
15
16
 
16
17
 
18
+ def _today_log(root):
19
+ return root / "app" / "logs" / f"app-{date.today():%Y-%m-%d}.log"
20
+
21
+
17
22
  @pytest.fixture
18
23
  def logging_cwd(tmp_path, monkeypatch):
19
24
  monkeypatch.chdir(tmp_path)
@@ -30,7 +35,7 @@ def test_configure_logging_writes_timestamped_file(logging_cwd):
30
35
  logger.info("hello-file-log")
31
36
  logger.complete()
32
37
 
33
- text = (logging_cwd / "app" / "logs" / "app.log").read_text(encoding="utf-8")
38
+ text = _today_log(logging_cwd).read_text(encoding="utf-8")
34
39
  assert "hello-file-log" in text
35
40
  assert TIMESTAMP.search(text)
36
41
  assert " | INFO |" in text
@@ -43,7 +48,7 @@ def test_uvicorn_access_lines_get_the_same_timestamp(logging_cwd):
43
48
  logging.getLogger("uvicorn.error").info("connection open")
44
49
  logger.complete()
45
50
 
46
- text = (logging_cwd / "app" / "logs" / "app.log").read_text(encoding="utf-8")
51
+ text = _today_log(logging_cwd).read_text(encoding="utf-8")
47
52
  assert 'GET / HTTP/1.1" 200 OK' in text
48
53
  assert "connection open" in text
49
54
  assert TIMESTAMP.search(text)
@@ -55,5 +60,15 @@ def test_configure_logging_is_idempotent(logging_cwd):
55
60
  logmod.configure_logging()
56
61
  logger.info("once")
57
62
  logger.complete()
58
- text = (logging_cwd / "app" / "logs" / "app.log").read_text(encoding="utf-8")
63
+ text = _today_log(logging_cwd).read_text(encoding="utf-8")
59
64
  assert text.count("once") == 1
65
+
66
+
67
+ def test_log_file_is_split_by_day(logging_cwd):
68
+ # 只按大小切时,量少的系统几个月都写在一个文件里;现在每天零点换新文件,旧文件保留 30 天。
69
+ logmod.configure_logging()
70
+ logger.info("daily")
71
+ logger.complete()
72
+ files = sorted(path.name for path in (logging_cwd / "app" / "logs").glob("app-*.log"))
73
+ assert files == [f"app-{date.today():%Y-%m-%d}.log"]
74
+ assert not (logging_cwd / "app" / "logs" / "app.log").exists()
@@ -0,0 +1,25 @@
1
+ # -*- coding: utf-8 -*-
2
+ """注册时上报的运行环境:自家包版本、前端自家包版本,不带路径和配置。"""
3
+
4
+ import json
5
+
6
+ from ys_base import __version__
7
+ from ys_base.server.runtime_info import runtime_info
8
+
9
+
10
+ def test_runtime_info_reports_own_packages_only(tmp_path):
11
+ web = tmp_path / "web"
12
+ (web / "dist").mkdir(parents=True)
13
+ (web / "package.json").write_text(
14
+ json.dumps({"dependencies": {"@ysgroup/ui": "0.1.46", "@ysgroup/core": "0.1.27", "vue": "3.5.0"}}),
15
+ encoding="utf-8",
16
+ )
17
+ info = runtime_info(web / "dist", started_at=1.0)
18
+ assert info["packages"]["ys-base"] == __version__
19
+ assert info["web_packages"] == {"@ysgroup/core": "0.1.27", "@ysgroup/ui": "0.1.46"}
20
+ assert info["started_at"] == 1.0 and info["python"] and info["hostname"]
21
+ assert str(tmp_path) not in json.dumps(info)
22
+
23
+
24
+ def test_runtime_info_without_package_json(tmp_path):
25
+ assert runtime_info(tmp_path / "web" / "dist")["web_packages"] == {}
@@ -1,4 +1,4 @@
1
1
  # -*- coding: utf-8 -*-
2
2
  """YS 统一 SDK:契约模型 / auth 客户端与差量同步 / 应用服务骨架。"""
3
3
 
4
- __version__ = "0.2.2"
4
+ __version__ = "0.2.3"
@@ -63,6 +63,7 @@ class AuthClient(WsRpcClient):
63
63
  app_version: str = "",
64
64
  instance_id: str = "",
65
65
  pending_page: str = "",
66
+ runtime: dict[str, Any] | None = None,
66
67
  **kwargs: Any,
67
68
  ):
68
69
  super().__init__(uri, **kwargs)
@@ -71,6 +72,8 @@ class AuthClient(WsRpcClient):
71
72
  self.app_version = app_version
72
73
  # 待处理落地页,注册时上报;空串表示用系统消息页。
73
74
  self.pending_page = normalize_pending_page(pending_page)
75
+ # 运行环境(Python、自家包版本、主机名等),注册时上报给 Auth 的应用运行状态面板。
76
+ self.runtime = dict(runtime or {})
74
77
  self.instance_id = instance_id.strip() or uuid.uuid4().hex
75
78
  if len(self.instance_id) > 200:
76
79
  raise ValueError("AuthClient instance_id 不能超过 200 个字符")
@@ -222,6 +225,7 @@ class AuthClient(WsRpcClient):
222
225
  "app_version": self.app_version,
223
226
  "pending_page": self.pending_page,
224
227
  "instance_id": self.instance_id,
228
+ "runtime": self.runtime,
225
229
  "applied_authorization_version": applied_authorization_version,
226
230
  },
227
231
  )
@@ -34,6 +34,7 @@ from ys_base.server.http_errors import install_http_error_handlers
34
34
  from ys_base.server.jwt_verify import JwtVerifier
35
35
  from ys_base.server.logging import configure_logging, new_request_id
36
36
  from ys_base.server.router import EventRouter
37
+ from ys_base.server.runtime_info import runtime_info
37
38
  from ys_base.store import MongoStore
38
39
  from ys_base.store.base import LOCAL_USERS_TABLE, LocalStore
39
40
  from ys_base.ws.rpc_client import YsRejected
@@ -186,6 +187,7 @@ class AppServer:
186
187
  注册时上报给 Auth,由 Auth 拼跳转地址。
187
188
  """
188
189
  configure_logging()
190
+ self.started_at = time.time()
189
191
  self.settings = settings
190
192
  self.app_version = app_version
191
193
  self.pending_page = normalize_pending_page(pending_page)
@@ -306,6 +308,7 @@ class AppServer:
306
308
  delta_sync=self.delta,
307
309
  app_version=self.app_version,
308
310
  pending_page=self.pending_page,
311
+ runtime=runtime_info(self.settings.web_dir, self.started_at),
309
312
  )
310
313
  self.auth.on_revoked(self._on_revoked)
311
314
  self.auth.on_app_profile(self._broadcast_app_profile)
@@ -547,6 +550,10 @@ class AppServer:
547
550
  return
548
551
  try:
549
552
  forwarded = data | {"app_name": self.settings.app_name} if event == "login" else data
553
+ if event in ("login", "exchange_sso_code"):
554
+ # 浏览器的地址由本服务填写(覆盖浏览器自带的同名字段),Auth 用它记登录来源、按来源限频。
555
+ client = getattr(ws, "client", None)
556
+ forwarded = forwarded | {"client_ip": str(getattr(client, "host", "") or "")}
550
557
  result = await self.auth.call(event, forwarded)
551
558
  if event in ("login", "exchange_sso_code", "refresh") and isinstance(result, dict):
552
559
  login_user = result.get("user", {}) or {}
@@ -1,5 +1,5 @@
1
1
  # -*- coding: utf-8 -*-
2
- """loguru 进程级配置:stderr + app/logs 落盘,接管标准库/uvicorn。"""
2
+ """loguru 进程级配置:stderr + app/logs 按天落盘,接管标准库/uvicorn。"""
3
3
 
4
4
  from __future__ import annotations
5
5
 
@@ -13,7 +13,9 @@ from loguru import logger
13
13
  _CONFIGURED = False
14
14
 
15
15
  LOG_DIR = Path("app") / "logs"
16
- LOG_FILE = LOG_DIR / "app.log"
16
+ # 每天一个文件 app-YYYY-MM-DD.log,零点(容器时区,部署镜像为上海)切换;只保留最近 LOG_RETENTION 天。
17
+ LOG_FILE = LOG_DIR / "app-{time:YYYY-MM-DD}.log"
18
+ LOG_RETENTION = "30 days"
17
19
 
18
20
  LOG_FORMAT = (
19
21
  "{time:YYYY-MM-DD HH:mm:ss.SSS} | {level:<8} | {name}:{function}:{line} | "
@@ -53,7 +55,7 @@ def _intercept_stdlib() -> None:
53
55
  def configure_logging() -> None:
54
56
  """每个进程只配置一次:enqueue 异步写、关闭 diagnose/backtrace。
55
57
 
56
- 同时写入标准错误与工作目录相对路径 ``app/logs/app.log``。
58
+ 同时写入标准错误与工作目录相对路径 ``app/logs/app-YYYY-MM-DD.log``(每天零点切新文件)。
57
59
  只读容器写文件失败时仍保留 stderr,不阻止启动。
58
60
  """
59
61
  global _CONFIGURED
@@ -78,11 +80,11 @@ def configure_logging() -> None:
78
80
  diagnose=False,
79
81
  backtrace=False,
80
82
  colorize=False,
81
- rotation="10 MB",
82
- retention="14 days",
83
+ rotation="00:00",
84
+ retention=LOG_RETENTION,
83
85
  encoding="utf-8",
84
86
  )
85
- logger.info("日志写入 {} 与标准错误", LOG_FILE.resolve())
87
+ logger.info("日志按天写入 {} 与标准错误", LOG_DIR.resolve())
86
88
  except OSError:
87
89
  logger.warning("无法写入 {},仅保留标准错误输出", LOG_FILE)
88
90
  _intercept_stdlib()
@@ -0,0 +1,61 @@
1
+ # -*- coding: utf-8 -*-
2
+ """注册时上报给 Auth 的运行环境:Python、自家包版本、前端自家包版本、主机名、进程启动时间。
3
+
4
+ 只报版本号和主机名,不报路径、环境变量、配置或依赖全集。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import importlib
10
+ import json
11
+ import os
12
+ import platform
13
+ import socket
14
+ import time
15
+ from importlib import metadata
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ # 自家 Python 包:装了哪个报哪个(模块名 → 包名),版本取模块的 __version__,与发布号一致。
20
+ PYTHON_PACKAGES = {"ys_base": "ys-base", "ys_trade_sdk": "ys-trade-sdk"}
21
+ # 自家前端包:从 web/package.json 读精确锁定的版本(镜像里要带上这个文件)。
22
+ WEB_SCOPE = "@ysgroup/"
23
+
24
+
25
+ def _python_packages() -> dict[str, str]:
26
+ found: dict[str, str] = {}
27
+ for module, name in PYTHON_PACKAGES.items():
28
+ try:
29
+ version = getattr(importlib.import_module(module), "__version__", "") or metadata.version(name)
30
+ except (ImportError, metadata.PackageNotFoundError):
31
+ continue
32
+ found[name] = str(version)
33
+ return found
34
+
35
+
36
+ def _web_packages(web_dir: str | Path) -> dict[str, str]:
37
+ manifest = Path(web_dir).parent / "package.json"
38
+ try:
39
+ data = json.loads(manifest.read_text(encoding="utf-8"))
40
+ except (OSError, ValueError):
41
+ return {}
42
+ found: dict[str, str] = {}
43
+ for section in ("dependencies", "devDependencies"):
44
+ deps = data.get(section) if isinstance(data, dict) else None
45
+ if not isinstance(deps, dict):
46
+ continue
47
+ for name, version in deps.items():
48
+ if isinstance(name, str) and name.startswith(WEB_SCOPE) and isinstance(version, str):
49
+ found[name] = version.strip()
50
+ return dict(sorted(found.items()))
51
+
52
+
53
+ def runtime_info(web_dir: str | Path, started_at: float | None = None) -> dict[str, Any]:
54
+ return {
55
+ "python": platform.python_version(),
56
+ "packages": _python_packages(),
57
+ "web_packages": _web_packages(web_dir),
58
+ "hostname": socket.gethostname(),
59
+ "pid": os.getpid(),
60
+ "started_at": started_at if started_at is not None else time.time(),
61
+ }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes