feat: 区分未同步与无数据日期,回补可自动联网补拉
This commit is contained in:
@ -17,6 +17,7 @@ from larkx.storage.models import Message
|
||||
from sqlalchemy import func
|
||||
|
||||
from snooper_client import SnifferLarkClient as LarkClient
|
||||
from snooper_history import HistoryError, sync_all_chats_for_day
|
||||
from snooper_membership import (
|
||||
MembershipError,
|
||||
fetch_self_join_times,
|
||||
@ -111,6 +112,7 @@ def main():
|
||||
parser.add_argument("--weekly-through", help="先仅补齐此日期前已结束周的周记")
|
||||
parser.add_argument("--refresh-tagged-from", help="重新生成此日期起带缺周报/月报标签的日报")
|
||||
parser.add_argument("--daily-overwrite-from", help="覆盖此日期起的全部已有日报")
|
||||
parser.add_argument("--fetch-missing", action="store_true", help="对本地无消息且从未同步的日期先联网拉取,再判断是否生成")
|
||||
parser.add_argument("--state", default=str(DEFAULT_STATE_PATH))
|
||||
args = parser.parse_args()
|
||||
|
||||
@ -185,6 +187,38 @@ def main():
|
||||
filtered, _ = filter_rows_by_membership(rows, join_times)
|
||||
return bool(filtered)
|
||||
|
||||
def ensure_day_synced(day: date) -> None:
|
||||
"""Fetch a day's messages only when it has neither local data nor a sync mark."""
|
||||
if storage.is_day_synced(day.isoformat()):
|
||||
return
|
||||
_, day_start, day_end, tz = resolve_day(day.isoformat(), args.timezone)
|
||||
rows = storage.get_received_messages(
|
||||
int(day_start.timestamp()),
|
||||
int(day_end.timestamp()),
|
||||
exclude_chat_ids=exclude_chat_ids,
|
||||
include_outgoing=True,
|
||||
)
|
||||
if rows:
|
||||
return
|
||||
print(f"===== 联网拉取 {day} =====", flush=True)
|
||||
try:
|
||||
stats = sync_all_chats_for_day(
|
||||
LarkClient(LarkAuth()),
|
||||
storage,
|
||||
day,
|
||||
tz,
|
||||
batch_size=50,
|
||||
exclude_chat_ids=exclude_chat_ids,
|
||||
)
|
||||
except HistoryError as error:
|
||||
print(f"===== 联网拉取 {day} 失败: {error} =====", flush=True)
|
||||
return
|
||||
print(
|
||||
f"===== 联网拉取 {day} 完成:消息 {stats['matched']} 条,"
|
||||
f"失败会话 {stats['failed']} 个 =====",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
state = {
|
||||
"model": args.model,
|
||||
"start_date": start.isoformat(),
|
||||
@ -268,6 +302,9 @@ def main():
|
||||
_, natural_week_end = week_bounds(current_week)
|
||||
day_start = max(daily_start, month_start, current_week)
|
||||
day_end = min(month_end, natural_week_end)
|
||||
if args.fetch_missing:
|
||||
for offset in range((day_end - day_start).days + 1):
|
||||
ensure_day_synced(day_start + timedelta(days=offset))
|
||||
for day in missing_message_dates(
|
||||
day_start,
|
||||
day_end,
|
||||
|
||||
@ -214,4 +214,6 @@ def sync_all_chats_for_day(
|
||||
"error_type": type(error).__name__,
|
||||
}
|
||||
)
|
||||
if not stats["failed"] and hasattr(storage, "mark_day_synced"):
|
||||
storage.mark_day_synced(target_day.isoformat(), stats["matched"])
|
||||
return stats
|
||||
|
||||
@ -26,6 +26,17 @@ class SyncProgress(Base):
|
||||
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
|
||||
|
||||
|
||||
class DaySyncState(Base):
|
||||
"""Whether a calendar day has been fully synced, regardless of message count."""
|
||||
|
||||
__tablename__ = "day_sync_state"
|
||||
|
||||
sync_date = Column(String(10), primary_key=True)
|
||||
completed = Column(Integer, default=0)
|
||||
message_count = Column(Integer, default=0)
|
||||
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
|
||||
|
||||
|
||||
class SnifferStorage(Storage):
|
||||
def __init__(self, url: str | None = None):
|
||||
if url is None and not os.environ.get("LARKX_STORAGE_URL"):
|
||||
@ -247,3 +258,33 @@ class SnifferStorage(Storage):
|
||||
session.commit()
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
def mark_day_synced(self, sync_date: str, message_count: int) -> None:
|
||||
"""Record that a calendar day has been fully synced (even with 0 messages)."""
|
||||
session = self.Session()
|
||||
try:
|
||||
row = (
|
||||
session.query(DaySyncState)
|
||||
.filter_by(sync_date=sync_date)
|
||||
.first()
|
||||
)
|
||||
if not row:
|
||||
row = DaySyncState(sync_date=sync_date)
|
||||
session.add(row)
|
||||
row.completed = 1
|
||||
row.message_count = int(message_count)
|
||||
session.commit()
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
def is_day_synced(self, sync_date: str) -> bool:
|
||||
session = self.Session()
|
||||
try:
|
||||
row = (
|
||||
session.query(DaySyncState)
|
||||
.filter_by(sync_date=sync_date)
|
||||
.first()
|
||||
)
|
||||
return bool(row and row.completed)
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
@ -138,6 +138,57 @@ def test_sync_all_chats_for_day_excludes_configured_chat_before_history_pull():
|
||||
assert storage.get_messages("private-b") == []
|
||||
|
||||
|
||||
def test_sync_marks_day_synced_when_no_failures():
|
||||
from snooper_history import sync_all_chats_for_day
|
||||
|
||||
tz = ZoneInfo("Asia/Shanghai")
|
||||
start_ts = 1_792_000_000
|
||||
client = FakeClient(start_ts)
|
||||
client.auth = type("Auth", (), {"user_id": "self"})()
|
||||
storage = Storage(url="sqlite:///:memory:")
|
||||
|
||||
stats = sync_all_chats_for_day(
|
||||
client,
|
||||
storage,
|
||||
date(2026, 11, 3),
|
||||
tz,
|
||||
batch_size=2,
|
||||
start_ts=start_ts,
|
||||
end_ts=start_ts + 86_400,
|
||||
)
|
||||
|
||||
assert stats["failed"] == 0
|
||||
assert storage.is_day_synced("2026-11-03") is True
|
||||
assert storage.is_day_synced("2026-11-04") is False
|
||||
|
||||
|
||||
def test_sync_does_not_mark_day_synced_when_failures():
|
||||
from snooper_history import sync_all_chats_for_day
|
||||
|
||||
class FailingClient(FakeClient):
|
||||
def pull_history(self, chat_id, positions, **kwargs):
|
||||
raise RuntimeError("合成失败")
|
||||
|
||||
tz = ZoneInfo("Asia/Shanghai")
|
||||
start_ts = 1_792_000_000
|
||||
client = FailingClient(start_ts)
|
||||
client.auth = type("Auth", (), {"user_id": "self"})()
|
||||
storage = Storage(url="sqlite:///:memory:")
|
||||
|
||||
stats = sync_all_chats_for_day(
|
||||
client,
|
||||
storage,
|
||||
date(2026, 11, 3),
|
||||
tz,
|
||||
batch_size=2,
|
||||
start_ts=start_ts,
|
||||
end_ts=start_ts + 86_400,
|
||||
)
|
||||
|
||||
assert stats["failed"] >= 1
|
||||
assert storage.is_day_synced("2026-11-03") is False
|
||||
|
||||
|
||||
def test_history_failure_log_identifies_chat_without_sensitive_error_body(tmp_path):
|
||||
from snooper_history import (
|
||||
format_history_failures,
|
||||
|
||||
Reference in New Issue
Block a user