-
Notifications
You must be signed in to change notification settings - Fork 535
fix: 提升本地存储写入可靠性 #1754
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
SengokuCola
merged 2 commits into
Mai-with-u:dev
from
liuwanwan1:fix/local-store-atomic-save
May 26, 2026
Merged
fix: 提升本地存储写入可靠性 #1754
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| from pathlib import Path | ||
| from types import ModuleType | ||
|
|
||
| import importlib | ||
| import json | ||
|
|
||
| import pytest | ||
|
|
||
|
|
||
| def _load_local_store_module(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> ModuleType: | ||
| """在临时工作目录中加载本地存储模块,避免全局单例写入项目目录。""" | ||
| monkeypatch.chdir(tmp_path) | ||
| import src.manager.local_store_manager as local_store_module | ||
|
|
||
| return importlib.reload(local_store_module) | ||
|
|
||
|
|
||
| class TestLocalStoreManager: | ||
| """本地存储读写测试。""" | ||
|
|
||
| def test_creates_store_file_without_parent_directory( | ||
| self, | ||
| tmp_path: Path, | ||
| monkeypatch: pytest.MonkeyPatch, | ||
| ) -> None: | ||
| """传入裸文件名时也应能创建本地存储文件。""" | ||
| local_store_module = _load_local_store_module(tmp_path, monkeypatch) | ||
|
|
||
| manager = local_store_module.LocalStoreManager("local_store.json") | ||
| manager["answer"] = 42 | ||
|
|
||
| store_path = tmp_path / "local_store.json" | ||
| assert store_path.exists() | ||
| assert json.loads(store_path.read_text(encoding="utf-8")) == {"answer": 42} | ||
|
|
||
| def test_backs_up_broken_json_before_rebuild( | ||
| self, | ||
| tmp_path: Path, | ||
| monkeypatch: pytest.MonkeyPatch, | ||
| ) -> None: | ||
| """损坏的 JSON 应先备份,再重建为空本地存储。""" | ||
| local_store_module = _load_local_store_module(tmp_path, monkeypatch) | ||
| store_path = tmp_path / "data" / "local_store.json" | ||
| store_path.parent.mkdir(parents=True, exist_ok=True) | ||
| store_path.write_text("{broken", encoding="utf-8") | ||
|
|
||
| manager = local_store_module.LocalStoreManager(str(store_path)) | ||
|
|
||
| assert manager.store == {} | ||
| assert json.loads(store_path.read_text(encoding="utf-8")) == {} | ||
| assert (tmp_path / "data" / "local_store.json.corrupt").read_text(encoding="utf-8") == "{broken" | ||
|
|
||
| def test_failed_save_keeps_original_file_and_cleans_temp_file( | ||
| self, | ||
| tmp_path: Path, | ||
| monkeypatch: pytest.MonkeyPatch, | ||
| ) -> None: | ||
| """保存失败时不应留下半写入文件或临时文件。""" | ||
| local_store_module = _load_local_store_module(tmp_path, monkeypatch) | ||
| store_path = tmp_path / "data" / "local_store.json" | ||
| store_path.parent.mkdir(parents=True, exist_ok=True) | ||
| store_path.write_text('{"stable": "value"}\n', encoding="utf-8") | ||
| manager = local_store_module.LocalStoreManager(str(store_path)) | ||
|
|
||
| def _raise_dump_error(*_args, **_kwargs) -> None: | ||
| raise RuntimeError("dump failed") | ||
|
|
||
| monkeypatch.setattr(local_store_module.json, "dump", _raise_dump_error) | ||
|
|
||
| manager.store["new"] = "value" | ||
| with pytest.raises(RuntimeError, match="dump failed"): | ||
| manager.save_local_store() | ||
|
|
||
| assert store_path.read_text(encoding="utf-8") == '{"stable": "value"}\n' | ||
| assert list(store_path.parent.glob(".local_store.json.*.tmp")) == [] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
补齐读取阶段的
OSError兜底,避免启动时直接失败当前只捕获了
JSONDecodeError/ValueError。如果这里遇到PermissionError、短暂 I/O 异常等OSError,会直接中断初始化,影响可用性。建议单独处理OSError,至少回退到内存空存储并记录日志,而不是让进程在启动阶段失败。建议修改
try: with file_path.open("r", encoding="utf-8") as f: loaded_store = json.load(f) if not isinstance(loaded_store, dict): raise ValueError("本地存储根节点必须是 JSON 对象") self.store = loaded_store logger.info("全都记起来了!") except (json.JSONDecodeError, ValueError) as exc: logger.warning("啊咧?记事本被弄脏了,正在重建记事本......") logger.debug(f"本地存储文件无法读取: {exc}") self._backup_broken_store(file_path) self.store = {} self._write_store_atomically(file_path, self.store) logger.info("记事本重建成功!") + except OSError as exc: + logger.warning("本地存储文件读取失败,将使用空内存存储继续运行。") + logger.debug(f"读取本地存储时发生 I/O 异常: {exc}") + self.store = {}🤖 Prompt for AI Agents