DushuoServer 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,8 @@
1
+ """度朔服务端。"""
2
+
3
+
4
+ __appname__ = "度朔·服务端"
5
+ __version__ = "0.1.0"
6
+ __engname__ = "Dushuo Server"
7
+ __descrpt__ = "度朔系统之服务端,提供度朔中心调度功能"
8
+
@@ -0,0 +1,6 @@
1
+ """允许通过 python -m dushuoserver 启动。"""
2
+
3
+ from .main import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
dushuoserver/app.py ADDED
@@ -0,0 +1,69 @@
1
+ """度朔服务端应用装配。"""
2
+
3
+ import asyncio
4
+ from collections.abc import AsyncGenerator
5
+ from contextlib import asynccontextmanager
6
+
7
+ from .logger import logger
8
+
9
+ logger.info("载入系统内容,导入内部引用库")
10
+
11
+ from fastapi import FastAPI, Request
12
+ from fastapi.responses import JSONResponse
13
+
14
+ from . import __appname__, __version__, __descrpt__
15
+ from .config import config
16
+ from .database import init_database
17
+ from .runtime import countdown_loop, state
18
+ from .services import execute_final_task
19
+ from .service.routers_health import router as health_router
20
+ from .service.routers_pairing import router as pairing_router
21
+ from .service.routers_activity import router as activity_router
22
+ from .service.routers_status import router as status_router
23
+ from .service.routers_config import router as config_router
24
+ from .service.routers_messages import router as messages_router
25
+
26
+ logger.info("载入网络服务端及路由模块")
27
+
28
+
29
+ @asynccontextmanager
30
+ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
31
+ """应用生命周期:初始化数据库并启动倒计时。"""
32
+ logger.info("正在初始化数据库")
33
+ init_database()
34
+
35
+ state.update_deadline()
36
+ state.generate_pairing_key()
37
+ task = asyncio.create_task(countdown_loop(execute_final_task))
38
+ logger.info("服务启动完成,死亡判定倒计时与配对窗口已开启")
39
+
40
+ try:
41
+ yield
42
+ finally:
43
+ task.cancel()
44
+ logger.info("服务正在关闭")
45
+
46
+
47
+ app = FastAPI(
48
+ title=__appname__,
49
+ description=__descrpt__,
50
+ version=__version__,
51
+ lifespan=lifespan,
52
+ )
53
+
54
+ app.include_router(health_router)
55
+ app.include_router(pairing_router)
56
+ app.include_router(activity_router)
57
+ app.include_router(status_router)
58
+ app.include_router(config_router)
59
+ app.include_router(messages_router)
60
+
61
+
62
+ @app.exception_handler(Exception)
63
+ def unhandled_exception(request: Request, exc: Exception) -> JSONResponse:
64
+ """统一处理未捕获异常。"""
65
+ logger.error("发生未捕获异常 `{}` `{}`".format(request.method, request.url.path))
66
+ return JSONResponse(
67
+ status_code=500,
68
+ content={"detail": "服务器内部错误"},
69
+ )
dushuoserver/config.py ADDED
@@ -0,0 +1,121 @@
1
+ """度朔服务端配置定义。"""
2
+
3
+ from sys import version_info as python_version, argv as cli_args
4
+ from pathlib import Path
5
+ from typing import Any, Annotated, Literal
6
+
7
+ from pydantic import BaseModel, Field, field_serializer, field_validator
8
+
9
+ import tomli_w
10
+
11
+ if python_version >= (3, 11):
12
+ import tomllib
13
+ else:
14
+ import tomli as tomllib # pyright: ignore[reportMissingImports]
15
+
16
+ class DeshuoConfigBaseModel(BaseModel):
17
+
18
+ def update(self, key: str, value: Any):
19
+ """更新运行时参数。"""
20
+ if key in self.model_fields_set: # 检测字段是否存在
21
+ if isinstance(value, value_type := getattr(self, key).__class__):
22
+ setattr(self, key, value)
23
+ return
24
+ raise TypeError("参数`{}`不符合`{}`的类型要求。".format(key, value_type))
25
+ raise ValueError("`{}`不是一个运行时参数")
26
+
27
+
28
+ class UvicronConfig(DeshuoConfigBaseModel):
29
+ """Uvicorn 配置"""
30
+
31
+ workers: int = 1
32
+ """Uvicorn 工作进程数"""
33
+ hot_reload: bool = False
34
+ """是否启用 Uvicorn 热重载"""
35
+ access_log: bool = True
36
+ """是否启用 Uvicorn 访问日志"""
37
+
38
+
39
+ class RuntimeConfig(DeshuoConfigBaseModel):
40
+ """运行时参数配置"""
41
+
42
+ activity_cache_duration: int = 86400
43
+ """客户端活动消息的缓存时长(秒)"""
44
+ death_countdown: int = 86400 # 死亡倒计时
45
+ """死亡判定倒计时(秒)"""
46
+ execution_task: str = ""
47
+ """最终任务执行命令"""
48
+ message_cache_duration: int = 3600
49
+ """短报文消息缓存时间(秒)"""
50
+ pairing_window_time: int = 300
51
+ """配对窗口时长(秒)"""
52
+ signature_time_tolerance: int = 300
53
+ """签名时间容差(秒)"""
54
+
55
+
56
+ class ServerConfig(DeshuoConfigBaseModel):
57
+ """服务端配置。"""
58
+
59
+ # 服务参数
60
+ host_address: str = "0.0.0.0"
61
+ """监听地址"""
62
+ host_port: int = 18470
63
+ """监听端口"""
64
+ log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = Field(
65
+ default="INFO", description="全局日志等级"
66
+ )
67
+ """全局日志等级"""
68
+ db_path: Path = Field(default=Path("dushuodb.sqlite3"), description="数据库文件路径")
69
+ """数据库文件路径"""
70
+
71
+ uvicron: UvicronConfig = Field(default_factory=UvicronConfig)
72
+ """Uvicorn 配置"""
73
+ runtime: RuntimeConfig = Field(default_factory=RuntimeConfig)
74
+ """运行时参数配置"""
75
+
76
+ # 校验 log_level 字段时(读入时),进行转换
77
+ @field_validator("log_level", mode="before")
78
+ @staticmethod
79
+ def _normalize_log_level(v: object) -> object:
80
+ if isinstance(v, str):
81
+ v = v.upper()
82
+ if v in ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'):
83
+ return v
84
+ else:
85
+ print(
86
+ "【***】传入的日志等级参数`{}`无效,现已切换为`DEBUG`等级。".format(v)
87
+ )
88
+ return "DEBUG"
89
+
90
+ # 序列化 db_path 字段时(输出时),进行转换
91
+ @field_serializer("db_path")
92
+ def serialize_db_path(self, value: Path) -> str:
93
+ return str(value)
94
+
95
+ @classmethod
96
+ def load_config(cls, config_file: Path | str) -> ServerConfig:
97
+ with open(config_file, "rb") as f:
98
+ return cls.model_validate(tomllib.load(f))
99
+
100
+ def save_config(self, config_file: Path | str) -> None:
101
+ with open(config_file, "wb") as f:
102
+ tomli_w.dump(self.model_dump(), f)
103
+
104
+ def dump_as_toml(self) -> str:
105
+ return tomli_w.dumps(self.model_dump())
106
+
107
+
108
+ config = ServerConfig()
109
+
110
+
111
+ if __name__ == "__main__":
112
+
113
+ if cli_args:
114
+ print("【***】加载配置文件:", cli_args[1])
115
+ config = ServerConfig.load_config(cli_args[1])
116
+ # config.runtime.update("death_countdown", 5454)
117
+
118
+ print(config.dump_as_toml())
119
+ print(config.model_dump())
120
+
121
+ # print(config.runtime.model_dump())
@@ -0,0 +1,211 @@
1
+ """度朔服务端数据库访问层。"""
2
+
3
+ import sqlite3
4
+ import time
5
+ from collections.abc import Generator
6
+ from contextlib import contextmanager
7
+ from typing import Any, Optional
8
+
9
+ from .config import config, RuntimeConfig
10
+ from .logger import logger
11
+
12
+
13
+ @contextmanager
14
+ def get_connection() -> Generator[sqlite3.Connection, None, None]:
15
+ """创建一个启用行工厂的 SQLite 连接。
16
+
17
+ 使用上下文管理器确保连接在使用后关闭,避免 Windows 上文件被占用。
18
+ """
19
+ conn = sqlite3.connect(config.db_path)
20
+ conn.row_factory = sqlite3.Row
21
+ try:
22
+ yield conn
23
+ finally:
24
+ conn.close()
25
+
26
+
27
+ def init_database() -> None:
28
+ """初始化数据库表结构并写入默认配置。"""
29
+ global config
30
+ logger.info("数据库初始化")
31
+ with get_connection() as conn:
32
+ conn.execute("""
33
+ CREATE TABLE IF NOT EXISTS rtconfig (
34
+ key TEXT PRIMARY KEY,
35
+ value TEXT NOT NULL
36
+ )
37
+ """)
38
+ conn.execute("""
39
+ CREATE TABLE IF NOT EXISTS activities (
40
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
41
+ client_id TEXT NOT NULL,
42
+ activity TEXT,
43
+ created_at REAL NOT NULL
44
+ )
45
+ """)
46
+ conn.execute("""
47
+ CREATE TABLE IF NOT EXISTS messages (
48
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
49
+ content TEXT NOT NULL,
50
+ created_at REAL NOT NULL
51
+ )
52
+ """)
53
+ conn.execute("""
54
+ CREATE TABLE IF NOT EXISTS message_fetches (
55
+ device_id TEXT NOT NULL,
56
+ message_id INTEGER NOT NULL,
57
+ fetched_at REAL NOT NULL,
58
+ PRIMARY KEY (device_id, message_id)
59
+ )
60
+ """)
61
+ conn.execute("""
62
+ CREATE TABLE IF NOT EXISTS clients (
63
+ client_id TEXT PRIMARY KEY,
64
+ public_key TEXT NOT NULL,
65
+ paired_at REAL NOT NULL
66
+ )
67
+ """)
68
+
69
+ conn.commit()
70
+
71
+ # 运行时参数确认
72
+ runtime_config_rows = dict(
73
+ conn.execute("SELECT key, value FROM rtconfig").fetchall()
74
+ )
75
+
76
+ for key, value in config.runtime.model_dump(mode="json").items():
77
+ if key not in runtime_config_rows:
78
+ conn.execute(
79
+ "INSERT INTO rtconfig (key, value) VALUES (?, ?)",
80
+ (key, value),
81
+ )
82
+ # conn.execute(
83
+ # "INSERT OR IGNORE INTO config (key, value) VALUES (?, ?)",
84
+ # (key, value),
85
+ # )
86
+
87
+ conn.commit()
88
+
89
+ # 重新读取数据库中的运行时参数,保证内存与数据库一致
90
+ runtime_config_rows = dict(
91
+ conn.execute("SELECT key, value FROM rtconfig").fetchall()
92
+ )
93
+
94
+ config.runtime = config.runtime.model_validate(runtime_config_rows)
95
+
96
+
97
+ def set_config_value(key: str, value: Any) -> None:
98
+ global config
99
+ config.runtime.update(key, value)
100
+ """写入或更新一个配置项。"""
101
+ with get_connection() as conn:
102
+ conn.execute(
103
+ "INSERT INTO rtconfig (key, value) VALUES (?, ?) "
104
+ "ON CONFLICT(key) DO UPDATE SET value = excluded.value",
105
+ (key, config.runtime.model_dump(mode="json")[key]),
106
+ )
107
+ conn.commit()
108
+
109
+
110
+ def cleanup_activities(retention_seconds: int) -> None:
111
+ """删除超过保留时间的数字活动记录。"""
112
+ cutoff = time.time() - retention_seconds
113
+ with get_connection() as conn:
114
+ conn.execute("DELETE FROM activities WHERE created_at < ?", (cutoff,))
115
+ conn.commit()
116
+
117
+
118
+ def insert_activity(client_id: str, activity: str, created_at: float) -> None:
119
+ """记录一条客户端数字活动。"""
120
+ with get_connection() as conn:
121
+ conn.execute(
122
+ "INSERT INTO activities (client_id, activity, created_at) VALUES (?, ?, ?)",
123
+ (client_id, activity, created_at),
124
+ )
125
+ conn.commit()
126
+
127
+
128
+ def cleanup_messages(cache_seconds: int) -> None:
129
+ """删除过期短报文及其设备获取记录。"""
130
+ cutoff = time.time() - cache_seconds
131
+ with get_connection() as conn:
132
+ conn.execute("DELETE FROM messages WHERE created_at < ?", (cutoff,))
133
+ conn.execute(
134
+ "DELETE FROM message_fetches WHERE message_id NOT IN (SELECT id FROM messages)"
135
+ )
136
+ conn.commit()
137
+
138
+
139
+ def get_latest_message() -> Optional[sqlite3.Row]:
140
+ """获取最新一条短报文。"""
141
+ with get_connection() as conn:
142
+ return conn.execute(
143
+ "SELECT id, content, created_at FROM messages ORDER BY id DESC LIMIT 1"
144
+ ).fetchone()
145
+
146
+
147
+ def insert_message(content: str, created_at: float) -> None:
148
+ """插入一条新的短报文。"""
149
+ with get_connection() as conn:
150
+ conn.execute(
151
+ "INSERT INTO messages (content, created_at) VALUES (?, ?)",
152
+ (content, created_at),
153
+ )
154
+ conn.commit()
155
+
156
+
157
+ def delete_message(message_id: int) -> None:
158
+ """删除指定短报文及其设备获取记录。"""
159
+ with get_connection() as conn:
160
+ conn.execute("DELETE FROM messages WHERE id = ?", (message_id,))
161
+ conn.execute("DELETE FROM message_fetches WHERE message_id = ?", (message_id,))
162
+ conn.commit()
163
+
164
+
165
+ def has_fetched_message(device_id: str, message_id: int) -> bool:
166
+ """判断设备是否已经获取过指定消息。"""
167
+ with get_connection() as conn:
168
+ row = conn.execute(
169
+ "SELECT 1 FROM message_fetches WHERE device_id = ? AND message_id = ?",
170
+ (device_id, message_id),
171
+ ).fetchone()
172
+ return row is not None
173
+
174
+
175
+ def mark_message_fetched(device_id: str, message_id: int, fetched_at: float) -> None:
176
+ """记录设备已获取某条消息。"""
177
+ with get_connection() as conn:
178
+ conn.execute(
179
+ "INSERT OR IGNORE INTO message_fetches (device_id, message_id, fetched_at) "
180
+ "VALUES (?, ?, ?)",
181
+ (device_id, message_id, fetched_at),
182
+ )
183
+ conn.commit()
184
+
185
+
186
+ def upsert_client(client_id: str, public_key: str) -> None:
187
+ """写入或更新一个客户端的公钥。"""
188
+ with get_connection() as conn:
189
+ conn.execute(
190
+ "INSERT INTO clients (client_id, public_key, paired_at) VALUES (?, ?, ?) "
191
+ "ON CONFLICT(client_id) DO UPDATE SET public_key = excluded.public_key",
192
+ (client_id, public_key, time.time()),
193
+ )
194
+ conn.commit()
195
+
196
+
197
+ def get_client_public_key(client_id: str) -> Optional[str]:
198
+ """获取一个客户端的公钥;客户端未配对时返回 None。"""
199
+ with get_connection() as conn:
200
+ row = conn.execute(
201
+ "SELECT public_key FROM clients WHERE client_id = ?",
202
+ (client_id,),
203
+ ).fetchone()
204
+ return None if row is None else row["public_key"]
205
+
206
+
207
+ def get_all_client_public_keys() -> list[tuple[str, str]]:
208
+ """列出全部已登记客户端的标识与公钥。"""
209
+ with get_connection() as conn:
210
+ rows = conn.execute("SELECT client_id, public_key FROM clients").fetchall()
211
+ return [(row["client_id"], row["public_key"]) for row in rows]
@@ -0,0 +1,76 @@
1
+ """
2
+ 计入所有使用的库之协议展示
3
+ """
4
+
5
+
6
+ def main():
7
+
8
+ from .logger import logger
9
+
10
+ from TrimLog import __version__ as TrimlogVersion
11
+ from uvicorn import __version__ as UvicornVersion
12
+ from pydantic import __version__ as PydanticVersion
13
+ from tomli_w import __version__ as TomliWVersion
14
+ from fastapi import __version__ as FastAPIVersion
15
+ from cryptography import (
16
+ __version__ as CryptographyVersion,
17
+ __copyright__ as CryptographyCopyright,
18
+ )
19
+
20
+ logger.license_shower(
21
+ lib_name="Uvicorn",
22
+ license_name="BSD-3-Clause license",
23
+ license_line="Copyright © 2017-present, Encode OSS Ltd. All rights reserved.",
24
+ lib_version=UvicornVersion,
25
+ include_startline=True,
26
+ include_endline=False,
27
+ )
28
+
29
+ logger.license_shower(
30
+ lib_name="pydantic",
31
+ license_name="MIT License",
32
+ license_line="Copyright (c) 2017 to present Pydantic Services Inc. and individual contributors.",
33
+ lib_version=PydanticVersion,
34
+ include_startline=True,
35
+ include_endline=False,
36
+ )
37
+
38
+ logger.license_shower(
39
+ lib_name="tomli_w",
40
+ license_name="MIT License",
41
+ license_line="Copyright (c) 2021 Taneli Hukkinen",
42
+ lib_version=TomliWVersion,
43
+ include_startline=True,
44
+ include_endline=False,
45
+ )
46
+
47
+ logger.license_shower(
48
+ lib_name="FastAPI",
49
+ license_name="MIT License",
50
+ license_line="Copyright (c) 2018 Sebastián Ramírez",
51
+ lib_version=FastAPIVersion,
52
+ include_startline=True,
53
+ include_endline=False,
54
+ )
55
+
56
+ logger.license_shower(
57
+ lib_name="cryptography",
58
+ license_name="Apache License, Version 2.0",
59
+ license_line=CryptographyCopyright,
60
+ lib_version=CryptographyVersion,
61
+ include_startline=True,
62
+ include_endline=False,
63
+ )
64
+
65
+ logger.license_shower(
66
+ lib_name="TrimLog",
67
+ license_name="Apache License, Version 2.0",
68
+ license_line="版权所有 © 2022-2026 FedDragon1, bgArray, Eilles",
69
+ lib_version=TrimlogVersion,
70
+ include_startline=True,
71
+ include_endline=True,
72
+ )
73
+
74
+
75
+ if __name__ == "__main__":
76
+ main()
dushuoserver/logger.py ADDED
@@ -0,0 +1,34 @@
1
+ """度朔服务端的日志模块"""
2
+
3
+ from TrimLog import object_constants, logger, log__init__
4
+ from . import __appname__, __version__
5
+
6
+ # 调试模式,在正式发布之前须要关闭
7
+ DEBUGGING = True
8
+
9
+ osc = object_constants.ObjectStateConstant(
10
+ is_debugging=DEBUGGING,
11
+ logging_project_name=__appname__,
12
+ logging_project_version=__version__,
13
+ is_this_a_release=not DEBUGGING,
14
+ logging_exit_exec=lambda x: print(
15
+ (
16
+ "[EXTREME CRITICAL ERROR] 运行时严重错误(`{}`:`{}`)"
17
+ ",本程序无法继续运行,请查阅日志文件:`{}`,特别关注以下错误信息:\n{}"
18
+ ).format(
19
+ x.exception_type, x.exception_value, x.log_file_path, x.message_content
20
+ )
21
+ ),
22
+ )
23
+ # print(osc.exit_execution)
24
+ osc.set_console(logger.console)
25
+
26
+ log__init__(osc, False)
27
+
28
+ logger.is_logging = True
29
+ logger.suffix = ".dss"
30
+ logger.is_tips = True
31
+ logger.printing = not osc.is_release
32
+ logger.license_level = "INFO"
33
+
34
+ logger.baseinfo_shower()