fix(notify): stop duplicate Telegram sends on slow-disk timeouts
- _tg_call: split connect-phase failure (UNSENT, safe to fall back) from post-connect timeouts / 5xx (ASSUME_SENT, never resend). urllib merged both into one URLError, so a lost response after a delivered photo triggered the URL fallback and sent the same listing twice. - /data/sent_ledger.json idempotency ledger keyed by id: and normalised product_url: blocks re-sends even when the notified PATCH fails; entries still pending in NocoDB are never evicted; .bak fallback for torn writes. - notified/skip_notify now written as one batch PATCH per tick and the 21 per-watch last_checked_at writes merged into one: tick body 90s -> 7s. - MAX_SEND_PER_TICK=15 with 1.5s spacing keeps a backlog drain under the Telegram per-chat rate limit and inside the health-check window. - health.json now reports sent/healed/silenced/deferred/patch_ok/ledger_size.
This commit is contained in:
1 parent
526b0f78da
commit
98d38953a4
1 file changed
+366
-89
+366
-89
@@ -17,9 +17,11 @@ unhealthy on any failed extract / rate-limit / crash.
|
||||
|
||||
Stdlib only.
|
||||
"""
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
@@ -47,6 +49,24 @@ DEFAULT_INTERVAL_MIN = int(os.environ.get("DEFAULT_INTERVAL_MIN", "5"))
|
||||
# 同一 tick 内逐条抓取 watch URL 之间的最小间隔秒数(防瞬时并发打爆 Carousell)。
|
||||
FETCH_GAP_SECONDS = float(os.environ.get("FETCH_GAP_SECONDS", "1"))
|
||||
|
||||
# 通知发送节流 / 超时预算。宿主机磁盘慢时必须显式限定,否则一个 tick 会被拖到
|
||||
# 十几分钟,health.json 不更新 → HEALTHCHECK 判死并 SIGKILL → 发送中途被杀 → 重发。
|
||||
MAX_SEND_PER_TICK = int(os.environ.get("MAX_SEND_PER_TICK", "15")) # TG 单会话约 20 条/分钟
|
||||
SEND_INTERVAL_SECONDS = float(os.environ.get("SEND_INTERVAL_SECONDS", "1.5"))
|
||||
TG_CONNECT_TIMEOUT = float(os.environ.get("TG_CONNECT_TIMEOUT", "5"))
|
||||
TG_READ_TIMEOUT = float(os.environ.get("TG_READ_TIMEOUT", "25"))
|
||||
TG_UPLOAD_READ_TIMEOUT = float(os.environ.get("TG_UPLOAD_READ_TIMEOUT", "45"))
|
||||
# NocoDB 写超时不能给 120s:MySQL innodb_lock_wait_timeout 默认 50s,等更久只会
|
||||
# 拖长 tick。慢写靠账本兜底,下一 tick 自愈,不在原地重试。
|
||||
NOCODB_WRITE_TIMEOUT = int(os.environ.get("NOCODB_WRITE_TIMEOUT", "60"))
|
||||
NOCODB_READ_TIMEOUT = int(os.environ.get("NOCODB_READ_TIMEOUT", "20"))
|
||||
|
||||
# 幂等账本:Telegram 已经发过的商品记在这里,作为 notified 列之外的第二道保险。
|
||||
# 只有「发之前就查账本」才能挡住 PATCH 超时导致的下一 tick 重发。
|
||||
LEDGER_PATH = os.path.join(DATA_DIR, "sent_ledger.json")
|
||||
LEDGER_TTL_SECONDS = 7 * 86400
|
||||
LEDGER_MAX_ENTRIES = 4000
|
||||
|
||||
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/120.0 Safari/537.36")
|
||||
|
||||
@@ -189,14 +209,10 @@ def _send_photo_multipart(chat_id, image_bytes, filename, caption):
|
||||
body += file_field("photo", filename, image_bytes, "image/jpeg")
|
||||
body += ("--" + boundary + "--").encode("utf-8") + CRLF
|
||||
|
||||
url = "https://api.telegram.org/bot" + TELEGRAM_BOT_TOKEN + "/sendPhoto"
|
||||
req = urllib.request.Request(url, data=body, method="POST", headers={
|
||||
"User-Agent": UA,
|
||||
"Content-Type": "multipart/form-data; boundary=" + boundary,
|
||||
})
|
||||
with urllib.request.urlopen(req, timeout=30) as r:
|
||||
raw = r.read().decode("utf-8", errors="ignore")
|
||||
return r.status, raw
|
||||
# 走 _tg_call 而不是 urllib:只有它能区分「连接阶段就失败」和「已发出但响应丢了」。
|
||||
return _tg_call("sendPhoto", body,
|
||||
"multipart/form-data; boundary=" + boundary,
|
||||
read_timeout=TG_UPLOAD_READ_TIMEOUT)
|
||||
|
||||
|
||||
def _json(status_raw):
|
||||
@@ -204,9 +220,15 @@ def _json(status_raw):
|
||||
return status, (json.loads(raw) if raw else None)
|
||||
|
||||
|
||||
def nc(method, path, body=None):
|
||||
def nc(method, path, body=None, timeout=None, retries=None):
|
||||
"""NocoDB 调用。读快写慢,两者用不同的超时预算。"""
|
||||
if timeout is None:
|
||||
timeout = NOCODB_READ_TIMEOUT if method == "GET" else NOCODB_WRITE_TIMEOUT
|
||||
if retries is None:
|
||||
retries = 1 if method == "GET" else 0
|
||||
return _json(_http(method, f"{NOCODB_URL}{path}", body=body,
|
||||
headers={"xc-token": NOCODB_TOKEN}))
|
||||
headers={"xc-token": NOCODB_TOKEN},
|
||||
timeout=timeout, retries=retries))
|
||||
|
||||
|
||||
def nc_list_all(tid, fields=None, extra_query=""):
|
||||
@@ -237,18 +259,86 @@ def nc_list_all(tid, fields=None, extra_query=""):
|
||||
offset += limit
|
||||
|
||||
|
||||
def tg(method, payload):
|
||||
"""调用 Telegram Bot API。
|
||||
TG_SENT, TG_ASSUME_SENT, TG_UNSENT = "SENT", "ASSUME_SENT", "UNSENT"
|
||||
|
||||
注意:method 是 Telegram 的方法名(如 "sendMessage"),**不是** HTTP 动词。
|
||||
早期版本直接把它当 HTTP method 传下去,于是请求行变成
|
||||
`sendMessage /bot<token>/sendMessage HTTP/1.1` —— 非法动词,Telegram 边缘
|
||||
一律回 400。结果是所有走 sendMessage 的通知静默失败(带图卡的 sendPhoto
|
||||
走 multipart 自建请求,所以侥幸能用)。
|
||||
|
||||
def _tg_call(method, body, content_type, read_timeout=None):
|
||||
"""POST 到 Bot API,并把「确定没发出」和「结果不明」严格分开。
|
||||
|
||||
2026-11 事故:宿主机磁盘 stall 时 urllib 把「TCP 握手失败」和「请求已发出、
|
||||
响应读超时」混成同一个 URLError;旧代码一律当失败,于是降级到下一个方案 →
|
||||
同一条商品被发两次(日志:`multipart sendPhoto failed: URLError`)。
|
||||
http.client 能把两段拆开:
|
||||
|
||||
* connect() 阶段失败(DNS / 握手超时 / 连接被拒)→ Telegram 收到 0 字节
|
||||
→ UNSENT,可以安全降级或下一 tick 重试;
|
||||
* connect() 成功之后的 send/getresponse 异常,以及 5xx 网关超时 → 请求极
|
||||
可能已被收下并投递 → ASSUME_SENT,**绝不能再发一次**(宁可极小概率漏发);
|
||||
* 429 按 retry_after 有限等待;只有边缘 nginx 偶发的非 JSON 400 才重试。
|
||||
|
||||
method 是 Telegram 的方法名(sendMessage / sendPhoto),不是 HTTP 动词。
|
||||
返回 (state, detail)。
|
||||
"""
|
||||
return _json(_http(
|
||||
"POST", f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/{method}",
|
||||
body=payload))
|
||||
path = f"/bot{TELEGRAM_BOT_TOKEN}/{method}"
|
||||
read_timeout = read_timeout or TG_READ_TIMEOUT
|
||||
for attempt in range(3):
|
||||
conn = http.client.HTTPSConnection("api.telegram.org", timeout=TG_CONNECT_TIMEOUT)
|
||||
try:
|
||||
conn.connect()
|
||||
except Exception as e:
|
||||
conn.close()
|
||||
if attempt < 2:
|
||||
time.sleep(0.5 * (attempt + 1))
|
||||
continue
|
||||
return TG_UNSENT, f"connect failed: {type(e).__name__}: {e}"
|
||||
try:
|
||||
conn.sock.settimeout(read_timeout)
|
||||
conn.request("POST", path, body=body, headers={
|
||||
"User-Agent": UA,
|
||||
"Content-Type": content_type,
|
||||
"Content-Length": str(len(body)),
|
||||
})
|
||||
resp = conn.getresponse()
|
||||
raw = resp.read().decode("utf-8", errors="ignore")
|
||||
status = resp.status
|
||||
except Exception as e:
|
||||
sys.stderr.write(f"tg {method} ambiguous after connect (ASSUME_SENT): "
|
||||
f"{type(e).__name__}: {e}\n")
|
||||
return TG_ASSUME_SENT, f"post-connect: {type(e).__name__}: {e}"
|
||||
finally:
|
||||
try:
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if status == 200:
|
||||
return TG_SENT, raw
|
||||
if status == 400 and not raw.lstrip().startswith("{") and attempt < 2:
|
||||
time.sleep(0.5 * (attempt + 1))
|
||||
continue
|
||||
if status == 429 and attempt < 2:
|
||||
try:
|
||||
wait_s = int(json.loads(raw).get("parameters", {}).get("retry_after", 5))
|
||||
except Exception:
|
||||
wait_s = 5
|
||||
if wait_s <= 15:
|
||||
time.sleep(wait_s)
|
||||
continue
|
||||
return TG_UNSENT, f"429 retry_after={wait_s}"
|
||||
if status >= 500:
|
||||
sys.stderr.write(f"tg {method} HTTP {status} (ASSUME_SENT)\n")
|
||||
return TG_ASSUME_SENT, f"HTTP {status}"
|
||||
return TG_UNSENT, f"HTTP {status}: {raw[:200]}"
|
||||
|
||||
|
||||
def tg(method, payload):
|
||||
"""兼容旧调用:返回 (status, raw),ASSUME_SENT 记作 200。"""
|
||||
state, detail = _tg_call(method, json.dumps(payload).encode("utf-8"),
|
||||
"application/json")
|
||||
if state == TG_UNSENT:
|
||||
m = re.match(r"HTTP (\d{3})", detail)
|
||||
return (int(m.group(1)) if m else 0), detail
|
||||
return 200, detail
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -575,9 +665,25 @@ def insert_listings(listings_tid, rows):
|
||||
raise RuntimeError(f"insert listings failed: {out}")
|
||||
|
||||
|
||||
def update_checked(settings_tid, watch_id):
|
||||
nc("PATCH", f"/api/v2/tables/{settings_tid}/records",
|
||||
[{"Id": watch_id, "last_checked_at": iso_now()}])
|
||||
def update_checked(settings_tid, watch_ids):
|
||||
"""批量写 last_checked_at。
|
||||
|
||||
旧版每抓完一个 watch 就 PATCH 一次,一轮 21 个 watch = 21 次写事务;在
|
||||
RAID5 reshape 的慢盘上这正是 tick 被拖到分钟级的主因。合并成 1 次。
|
||||
"""
|
||||
if not watch_ids:
|
||||
return True
|
||||
iso = iso_now()
|
||||
try:
|
||||
st, raw = nc("PATCH", f"/api/v2/tables/{settings_tid}/records",
|
||||
[{"Id": i, "last_checked_at": iso} for i in watch_ids])
|
||||
except Exception as e:
|
||||
sys.stderr.write(f"update_checked failed (count={len(watch_ids)}): {e}\n")
|
||||
return False
|
||||
if st != 200:
|
||||
sys.stderr.write(f"update_checked HTTP {st}: {str(raw)[:200]}\n")
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def build_row(l, watch, notified=False):
|
||||
@@ -611,25 +717,121 @@ def build_row(l, watch, notified=False):
|
||||
# Telegram
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _tg_send(method, payload):
|
||||
"""发一条消息。返回 True = 已投递或疑已投递(不可再发)。"""
|
||||
if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID:
|
||||
return False
|
||||
try:
|
||||
tg(method, {"chat_id": TELEGRAM_CHAT_ID, **payload})
|
||||
return True
|
||||
except urllib.error.HTTPError as e:
|
||||
sys.stderr.write(f"telegram {method} failed: {e.code} {e.read()[:200]}\n")
|
||||
state, detail = _tg_call(method, json.dumps({"chat_id": TELEGRAM_CHAT_ID, **payload}).encode("utf-8"),
|
||||
"application/json")
|
||||
if state == TG_UNSENT:
|
||||
sys.stderr.write(f"telegram {method} not sent: {detail}\n")
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def send_telegram(text):
|
||||
_tg_send("sendMessage", {"text": text})
|
||||
|
||||
|
||||
def send_listing_from_record(rec):
|
||||
"""Send one listing notice from a NocoDB record.
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 通知幂等账本(防重复发送)
|
||||
# --------------------------------------------------------------------------- #
|
||||
_MEM_LEDGER = None
|
||||
|
||||
rec fields: title, price, condition, seller_name, product_url, image_url.
|
||||
Prefer photo; fall back to text-only if the image fails.
|
||||
|
||||
def normalize_product_url(url):
|
||||
"""剥掉 query/fragment:同一个商品被两个 watch 抓到、或带追踪后缀时仍算同一条。"""
|
||||
if not url:
|
||||
return ""
|
||||
try:
|
||||
p = urllib.parse.urlsplit(str(url).strip())
|
||||
path = (p.path or "").rstrip("/")
|
||||
return urllib.parse.urlunsplit((p.scheme.lower(), p.netloc.lower(), path, "", ""))
|
||||
except Exception:
|
||||
return str(url).strip()
|
||||
|
||||
|
||||
def ledger_keys(rec):
|
||||
keys = []
|
||||
rid = rec.get("Id")
|
||||
if rid is not None:
|
||||
keys.append(f"id:{rid}")
|
||||
clean = normalize_product_url(rec.get("product_url") or "")
|
||||
if clean:
|
||||
keys.append(f"url:{clean}")
|
||||
return keys
|
||||
|
||||
|
||||
def load_ledger():
|
||||
"""读账本:主文件坏了就用 .bak(宿主机满盘/掉电时会出现 0 字节)。"""
|
||||
global _MEM_LEDGER
|
||||
if _MEM_LEDGER is not None:
|
||||
return _MEM_LEDGER
|
||||
for path in (LEDGER_PATH, LEDGER_PATH + ".bak"):
|
||||
try:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
raw = f.read().strip()
|
||||
if not raw:
|
||||
continue
|
||||
data = json.loads(raw)
|
||||
if isinstance(data, dict):
|
||||
_MEM_LEDGER = {str(k): float(v) for k, v in data.items()}
|
||||
return _MEM_LEDGER
|
||||
except FileNotFoundError:
|
||||
continue
|
||||
except Exception as e:
|
||||
sys.stderr.write(f"ledger load failed ({path}): {e}\n")
|
||||
_MEM_LEDGER = {}
|
||||
return _MEM_LEDGER
|
||||
|
||||
|
||||
def save_ledger(ledger, protected=None, durable=False):
|
||||
"""写账本。
|
||||
|
||||
durable=False:每条发完就调一次,只进 Page Cache(毫秒级,防进程被杀);
|
||||
durable=True:每轮 finally 调一次,做 .bak + fsync(防掉电)。宿主机 99% 满且
|
||||
RAID5 reshape 中,每条都 fsync 会把 I/O 抢死,所以只在轮末落盘。
|
||||
protected:本轮 NocoDB 里仍 notified=false 的 key,禁止被 TTL/容量淘汰 ——
|
||||
否则账本忘了它、数据库又没写回,下轮就是「诈尸重发」。
|
||||
"""
|
||||
protected = protected or set()
|
||||
now = time.time()
|
||||
if durable:
|
||||
for k in [k for k, ts in ledger.items()
|
||||
if now - ts > LEDGER_TTL_SECONDS and k not in protected]:
|
||||
ledger.pop(k, None)
|
||||
if len(ledger) > LEDGER_MAX_ENTRIES:
|
||||
removable = sorted(((k, ts) for k, ts in ledger.items() if k not in protected),
|
||||
key=lambda x: x[1])
|
||||
for k, _ in removable[:len(ledger) - LEDGER_MAX_ENTRIES]:
|
||||
ledger.pop(k, None)
|
||||
tmp = f"{LEDGER_PATH}.tmp.{os.getpid()}"
|
||||
try:
|
||||
os.makedirs(DATA_DIR, exist_ok=True)
|
||||
if durable and os.path.exists(LEDGER_PATH) and os.path.getsize(LEDGER_PATH) > 2:
|
||||
try:
|
||||
bak_tmp = LEDGER_PATH + ".bak.tmp"
|
||||
with open(LEDGER_PATH, "rb") as src, open(bak_tmp, "wb") as dst:
|
||||
dst.write(src.read())
|
||||
dst.flush()
|
||||
os.fsync(dst.fileno())
|
||||
os.replace(bak_tmp, LEDGER_PATH + ".bak")
|
||||
except Exception as e:
|
||||
sys.stderr.write(f"ledger bak warning: {e}\n")
|
||||
with open(tmp, "wb") as f:
|
||||
f.write(json.dumps(ledger, ensure_ascii=False).encode("utf-8"))
|
||||
f.flush()
|
||||
if durable:
|
||||
os.fsync(f.fileno())
|
||||
os.replace(tmp, LEDGER_PATH)
|
||||
except Exception as e:
|
||||
sys.stderr.write(f"ledger save failed (durable={durable}): {e}\n")
|
||||
|
||||
|
||||
def send_listing_from_record(rec):
|
||||
"""发一条商品通知。
|
||||
|
||||
返回 True = 已投递或疑已投递(**必须**入账本,不能再发);
|
||||
返回 False = 确定一个字都没发出去(可以下一 tick 重试)。
|
||||
"""
|
||||
title = rec.get("title") or "(no title)"
|
||||
price = rec.get("price") or ""
|
||||
@@ -647,89 +849,156 @@ def send_listing_from_record(rec):
|
||||
caption_lines.append(product_url)
|
||||
caption = "\n".join(caption_lines)
|
||||
thumb = rec.get("image_url") or ""
|
||||
|
||||
if thumb:
|
||||
# 方案1:下载图后 multipart 上传(最稳,Telegram 无需访问 carousell CDN)
|
||||
# 方案1:本地下载图后 multipart 上传。下载失败 = 确定没发,可安全降级。
|
||||
img_bytes = _download_image(thumb)
|
||||
if img_bytes:
|
||||
try:
|
||||
st, raw = _send_photo_multipart(
|
||||
TELEGRAM_CHAT_ID, img_bytes, "listing.jpg", caption)
|
||||
if st == 200:
|
||||
return True
|
||||
sys.stderr.write(f"multipart sendPhoto: HTTP {st}\n")
|
||||
except Exception as e:
|
||||
sys.stderr.write(f"multipart sendPhoto failed: {type(e).__name__}\n")
|
||||
# 方案2:退回让 Telegram 直接下载 URL
|
||||
if _tg_send("sendPhoto", {"photo": thumb, "caption": caption}):
|
||||
state, detail = _send_photo_multipart(
|
||||
TELEGRAM_CHAT_ID, img_bytes, "listing.jpg", caption)
|
||||
if state != TG_UNSENT:
|
||||
return True # SENT / ASSUME_SENT 都不许再发
|
||||
sys.stderr.write(f"multipart sendPhoto not sent ({detail}); fallback to URL\n")
|
||||
# 方案2:让 Telegram 自己下载 URL —— 仅在 multipart 确定未发出时才会到这里
|
||||
state, detail = _tg_call("sendPhoto", json.dumps(
|
||||
{"chat_id": TELEGRAM_CHAT_ID, "photo": thumb, "caption": caption}
|
||||
).encode("utf-8"), "application/json")
|
||||
if state != TG_UNSENT:
|
||||
return True
|
||||
# 方案3:纯文本
|
||||
sys.stderr.write(f"sendPhoto(url) not sent ({detail}); fallback to text\n")
|
||||
# 方案3:纯文本兜底
|
||||
return _tg_send("sendMessage", {"text": caption})
|
||||
|
||||
|
||||
def patch_listings(listings_tid, rows):
|
||||
"""批量 PATCH Listings:N 条通知只产生 1 次写事务(慢盘上这是数量级的差别)。"""
|
||||
if not rows:
|
||||
return True
|
||||
try:
|
||||
st, raw = nc("PATCH", f"/api/v2/tables/{listings_tid}/records", rows)
|
||||
except Exception as e:
|
||||
sys.stderr.write(f"patch_listings failed (count={len(rows)}): {e}\n")
|
||||
return False
|
||||
if st != 200:
|
||||
sys.stderr.write(f"patch_listings HTTP {st} (count={len(rows)}): {str(raw)[:200]}\n")
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def mark_notified(listings_tid, rec_ids):
|
||||
"""把已发通知的记录 notified 置 true。"""
|
||||
if not rec_ids:
|
||||
return
|
||||
updates = [{"Id": rid, "notified": True} for rid in rec_ids]
|
||||
nc("PATCH", f"/api/v2/tables/{listings_tid}/records", updates)
|
||||
"""兼容旧调用:把一组 Id 置 notified=true(内部走批量 PATCH)。"""
|
||||
patch_listings(listings_tid, [{"Id": rid, "notified": True} for rid in rec_ids])
|
||||
|
||||
|
||||
def send_pending_notifications(listings_tid, settings_tid, ignored_sellers_tid,
|
||||
ignored_keywords_tid, kw_fk_col):
|
||||
"""tick 末尾统一发:查 notified=false 的记录,逐条发(间隔 1s),发完置 true。
|
||||
"""tick 末尾统一发通知,返回本轮统计。
|
||||
|
||||
仅发「其 watch 仍 notify=true」的记录;watch 已关 notify 的则静默置 true。
|
||||
若 seller_name 落在 IgnoredSellers 忽略列表,或 title 命中该 watch
|
||||
(search_url)在 IgnoredKeywords 里的关键词(大小写不敏感),则置
|
||||
skip_notify=true + notified=true,不发 Telegram。
|
||||
三重防重(2026-11 事故后加固):
|
||||
1. 账本命中 → 已经发过(上轮 Telegram 成功但 PATCH 超时没写回)→ 只补写
|
||||
notified=true,绝不再发;
|
||||
2. 发送返回 True(含 ASSUME_SENT)就立刻入账本并快照落盘,PATCH 好不好
|
||||
都不影响下一轮判断;
|
||||
3. 单 tick 最多发 MAX_SEND_PER_TICK 条,剩下的留到下一 tick(防 TG 429 与
|
||||
tick 超时被 HEALTHCHECK 杀掉)。
|
||||
所有标记攒成一次批量 PATCH,避免 N 条通知产生 N 次慢盘写事务。
|
||||
"""
|
||||
# 加载所有 watch 的 notify 开关,key = search_title
|
||||
stats = {"sent": 0, "healed": 0, "silenced": 0, "deferred": 0, "patch_ok": True}
|
||||
|
||||
st, wrows = nc_list_all(settings_tid, fields="title,notify")
|
||||
if st != 200:
|
||||
return
|
||||
notify_by_title = {}
|
||||
for w in wrows:
|
||||
notify_by_title[w.get("title")] = bool(w.get("notify"))
|
||||
stats["patch_ok"] = False
|
||||
return stats
|
||||
notify_by_title = {w.get("title"): bool(w.get("notify")) for w in wrows}
|
||||
|
||||
# 每轮重新加载忽略列表,中途增删立即生效
|
||||
ignored = load_ignored_sellers(ignored_sellers_tid)
|
||||
ignored_kw_by_url = load_ignored_keywords(ignored_keywords_tid, settings_tid,
|
||||
kw_fk_col)
|
||||
|
||||
# 拉 notified=false 的记录(必须分页:单页 1000 行封顶,新记录在尾部)
|
||||
st, rows = nc_list_all(
|
||||
listings_tid,
|
||||
fields="Id,title,price,condition,seller_name,product_url,image_url,"
|
||||
"search_title,search_url,notified,skip_notify")
|
||||
if st != 200:
|
||||
return
|
||||
stats["patch_ok"] = False
|
||||
return stats
|
||||
pending = [r for r in rows if not r.get("notified")]
|
||||
|
||||
if not pending:
|
||||
return
|
||||
return stats
|
||||
|
||||
for rec in pending:
|
||||
seller = (rec.get("seller_name") or "").strip()
|
||||
title = (rec.get("title") or "").strip()
|
||||
search_url = (rec.get("search_url") or "").strip()
|
||||
kw_for_watch = ignored_kw_by_url.get(search_url, set())
|
||||
if seller in ignored or title_matches_keyword(title, kw_for_watch):
|
||||
# 命中忽略卖家/该 watch 的关键词:标记 skip_notify,静默置 notified,不发
|
||||
nc("PATCH", f"/api/v2/tables/{listings_tid}/records",
|
||||
[{"Id": rec["Id"], "skip_notify": True, "notified": True}])
|
||||
continue
|
||||
st_title = rec.get("search_title") or ""
|
||||
should_notify = notify_by_title.get(st_title, True)
|
||||
if should_notify:
|
||||
ok = send_listing_from_record(rec)
|
||||
ledger = load_ledger()
|
||||
# 这些 key 在 NocoDB 里仍是 notified=false —— 账本哪怕过期也不许淘汰它们
|
||||
protected = set()
|
||||
for r in pending:
|
||||
protected.update(ledger_keys(r))
|
||||
|
||||
batch = []
|
||||
|
||||
def flush():
|
||||
if not batch:
|
||||
return
|
||||
if patch_listings(listings_tid, batch):
|
||||
del batch[:]
|
||||
else:
|
||||
# 词条关了 notify:静默标记,不发
|
||||
ok = True
|
||||
# 只有发送成功(或无需发)才标记 notified=true;
|
||||
# 失败则保留 false,下个 tick 末尾自动重试。
|
||||
if ok:
|
||||
mark_notified(listings_tid, [rec["Id"]])
|
||||
time.sleep(1) # 最快 1 秒一条,防限流
|
||||
stats["patch_ok"] = False
|
||||
|
||||
try:
|
||||
for rec in pending:
|
||||
rid = rec.get("Id")
|
||||
keys = ledger_keys(rec)
|
||||
|
||||
# 1) 账本命中:已发过,只补写标记(自愈,不重发)
|
||||
if any(k in ledger for k in keys):
|
||||
batch.append({"Id": rid, "notified": True})
|
||||
stats["healed"] += 1
|
||||
if len(batch) >= 25:
|
||||
flush()
|
||||
continue
|
||||
|
||||
# 2) 忽略卖家 / 关键词:静默标记,不发
|
||||
seller = (rec.get("seller_name") or "").strip()
|
||||
title = (rec.get("title") or "").strip()
|
||||
search_url = (rec.get("search_url") or "").strip()
|
||||
kw_for_watch = ignored_kw_by_url.get(search_url, set())
|
||||
if seller in ignored or title_matches_keyword(title, kw_for_watch):
|
||||
now_ts = time.time()
|
||||
for k in keys:
|
||||
ledger[k] = now_ts
|
||||
batch.append({"Id": rid, "skip_notify": True, "notified": True})
|
||||
stats["silenced"] += 1
|
||||
continue
|
||||
|
||||
# 3) 该 watch 关了 notify:同样静默标记
|
||||
if not notify_by_title.get(rec.get("search_title") or "", True):
|
||||
now_ts = time.time()
|
||||
for k in keys:
|
||||
ledger[k] = now_ts
|
||||
batch.append({"Id": rid, "notified": True})
|
||||
stats["silenced"] += 1
|
||||
continue
|
||||
|
||||
# 4) 本轮已达发送上限:留给下一 tick,账本里没有它,下轮会再挑到
|
||||
if stats["sent"] >= MAX_SEND_PER_TICK:
|
||||
stats["deferred"] += 1
|
||||
continue
|
||||
|
||||
if send_listing_from_record(rec):
|
||||
now_ts = time.time()
|
||||
for k in keys:
|
||||
ledger[k] = now_ts
|
||||
# 先落一份无 fsync 快照(毫秒级),再谈 NocoDB 写回
|
||||
save_ledger(ledger, protected)
|
||||
batch.append({"Id": rid, "notified": True})
|
||||
stats["sent"] += 1
|
||||
if len(batch) >= 10:
|
||||
flush()
|
||||
time.sleep(SEND_INTERVAL_SECONDS)
|
||||
finally:
|
||||
# 轮末:账本带 fsync + .bak 落盘,剩余标记一次批量 PATCH
|
||||
save_ledger(ledger, protected, durable=True)
|
||||
flush()
|
||||
|
||||
return stats
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -812,6 +1081,7 @@ def run_tick(listings_tid, settings_tid, ignored_sellers_tid, ignored_keywords_t
|
||||
kw_fk_col, seen, last_run):
|
||||
failures = []
|
||||
new_total = 0
|
||||
checked_ids = []
|
||||
watches = load_watches(settings_tid)
|
||||
now = time.time()
|
||||
|
||||
@@ -843,14 +1113,17 @@ def run_tick(listings_tid, settings_tid, ignored_sellers_tid, ignored_keywords_t
|
||||
seen.add(PRODUCT_URL_TMPL.format(listing_id=l["listing_id"]))
|
||||
|
||||
new_total += len(fresh)
|
||||
update_checked(settings_tid, wid)
|
||||
checked_ids.append(wid)
|
||||
last_run[wid] = now
|
||||
# 同一 tick 内逐条抓取 watch URL 之间的最小间隔(默认 1s,env FETCH_GAP_SECONDS 可调)
|
||||
time.sleep(FETCH_GAP_SECONDS)
|
||||
|
||||
# 21 个 watch 的时间戳合并成 1 次批量 PATCH
|
||||
update_checked(settings_tid, checked_ids)
|
||||
|
||||
# 归档完成后,统一发送待通知的记录(解耦:归档成功才通知)
|
||||
send_pending_notifications(listings_tid, settings_tid, ignored_sellers_tid,
|
||||
ignored_keywords_tid, kw_fk_col)
|
||||
notif = send_pending_notifications(listings_tid, settings_tid, ignored_sellers_tid,
|
||||
ignored_keywords_tid, kw_fk_col)
|
||||
|
||||
# 只有失败占比达到阈值才算整轮故障;单个 watch 偶发软限流不报故障。
|
||||
# 阈值 1.0 = 全部 watch 失败才 ok=false(默认);0.0 = 任何失败都算。
|
||||
@@ -862,7 +1135,11 @@ def run_tick(listings_tid, settings_tid, ignored_sellers_tid, ignored_keywords_t
|
||||
err = f"[partial {len(failures)}/{n}] " + err
|
||||
return ok, err, {
|
||||
"watch_count": n, "new_this_tick": new_total,
|
||||
"failed_watches": len(failures)}
|
||||
"failed_watches": len(failures),
|
||||
"sent": notif.get("sent", 0), "healed": notif.get("healed", 0),
|
||||
"silenced": notif.get("silenced", 0), "deferred": notif.get("deferred", 0),
|
||||
"patch_ok": notif.get("patch_ok", True),
|
||||
"ledger_size": len(load_ledger())}
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
Reference in new issue
Block a user