- flush() no longer re-enters the 60s PATCH after a mid-loop failure (once it failed at batch>=10 every remaining record retried it, which could stall the tick until HEALTHCHECK killed it); it retries exactly once at the end. - silenced rows (ignored seller / keyword / watch notify=off) are no longer written to the ledger, so a failed PATCH re-runs the same silent branch next tick instead of healing to notified without skip_notify. Ledger now means 'actually delivered to Telegram' and nothing else. - success path order: ledger (memory) -> batch -> snapshot, and the finally block isolates save_ledger from flush so an ENOSPC cannot skip the DB write. - _tg_call accepts str bodies (Content-Length is bytes; str would have been latin-1 encoded and misread as ASSUME_SENT).
1186 lines
47 KiB
Python
1186 lines
47 KiB
Python
#!/usr/bin/env python3
|
||
"""Carousell new-listing monitor -> NocoDB archive + Telegram alerts.
|
||
|
||
Self-bootstrapping: on startup it ensures the NocoDB schema (Listings + Settings
|
||
tables) exists, then loops forever. Each tick it reads the watch list from the
|
||
Settings table, polls each enabled watch's Carousell search URL on its own
|
||
interval, dedupes by product_url (param-less listing URL), archives every listing
|
||
to NocoDB (title, numeric price, condition, image URL + thumbnail attachment,
|
||
seller, link, timestamps), and — after the first seed — alerts Telegram with
|
||
"<title>: N new listing(s)".
|
||
|
||
Secrets via env vars; operational knobs (enabled / notify / interval) live in the
|
||
NocoDB Settings table so they're adjustable from the UI without a redeploy.
|
||
|
||
Writes /data/health.json every tick; the Docker HEALTHCHECK flags the container
|
||
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
|
||
import urllib.parse
|
||
import urllib.request
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# Config (env)
|
||
# --------------------------------------------------------------------------- #
|
||
NOCODB_URL = os.environ.get("NOCODB_URL", "http://nocodb:10380").rstrip("/")
|
||
NOCODB_TOKEN = os.environ.get("NOCODB_TOKEN", "")
|
||
NOCODB_BASE_ID = os.environ.get("NOCODB_BASE_ID", "")
|
||
TELEGRAM_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN", "")
|
||
TELEGRAM_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID", "")
|
||
DATA_DIR = os.environ.get("DATA_DIR", "/data")
|
||
TICK_SECONDS = int(os.environ.get("TICK_SECONDS", "60"))
|
||
HEALTH_STALE_SECONDS = int(os.environ.get("HEALTH_STALE_SECONDS", "600"))
|
||
# 错误告警去抖:连续失败达到该次数才发 Telegram,恢复时发一条恢复通知。
|
||
# 目的:单个 watch 偶发 403/超时不会刷屏,但持续故障一定通知到人。
|
||
ERROR_ALERT_AFTER = int(os.environ.get("ERROR_ALERT_AFTER", "3"))
|
||
# 单个 watch 偶发失败(Carousell 软限流)不该把整轮判为故障:只有失败占比
|
||
# 达到该比例(默认全挂)才 ok=false。设为 1.0 = 全部失败才算故障;0.0 关闭。
|
||
FAILURE_RATIO_THRESHOLD = float(os.environ.get("FAILURE_RATIO_THRESHOLD", "1.0"))
|
||
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")
|
||
|
||
CONDITIONS = ["Brand new", "Like new", "Lightly used", "Well used", "Heavily used", "Used"]
|
||
# Carousell 不同类目对 condition 的写法不一:New ≈ Brand new;Used 是笼统二手。
|
||
CONDITION_MAP = {
|
||
"brand new": "Brand new",
|
||
"new": "Brand new",
|
||
"like new": "Like new",
|
||
"lightly used": "Lightly used",
|
||
"well used": "Well used",
|
||
"heavily used": "Heavily used",
|
||
"used": "Used",
|
||
}
|
||
PRODUCT_URL_TMPL = "https://www.carousell.com.my/p/{listing_id}/"
|
||
SELLER_URL_TMPL = "https://www.carousell.com.my/u/{username}/"
|
||
|
||
|
||
def strip_thumbnail_suffix(url):
|
||
"""去掉 Carousell 缩略图后缀 _progressive_thumbnail,得到高清原图 URL。
|
||
|
||
两种形态都去掉:
|
||
1) ..._progressive_thumbnail.jpg → ...jpg
|
||
2) ..._progressive_thumbnail → ...(无扩展名,仍是合法 JPEG)
|
||
"""
|
||
if not url:
|
||
return url
|
||
return url.replace("_progressive_thumbnail", "")
|
||
|
||
# Column definitions: table title -> list of (title, uidt)
|
||
LISTINGS_COLS = [
|
||
("product_url", "URL"),
|
||
("title", "SingleLineText"),
|
||
("price", "Decimal"),
|
||
("condition", "SingleSelect"), # options set via 2-pass below
|
||
("image_url", "URL"),
|
||
("image", "Attachment"),
|
||
("seller_name", "SingleLineText"),
|
||
("seller_url", "URL"),
|
||
("search_title", "SingleLineText"),
|
||
("search_url", "URL"),
|
||
("listed_at", "DateTime"),
|
||
("first_seen_at", "DateTime"),
|
||
("notified", "Checkbox"),
|
||
("skip_notify", "Checkbox"),
|
||
]
|
||
IGNORED_SELLERS_COLS = [
|
||
("seller_name", "SingleLineText"),
|
||
]
|
||
# 忽略关键词(per-watch):keyword 单行一条;watch=Link 指向 Settings 记录;
|
||
# search_url=Lookup 自动带出被链接 watch 的 Settings.url。
|
||
# 大小写不敏感,命中该 watch 的「标题」即跳过通知(仍归档)。
|
||
IGNORED_KEYWORDS_COLS = [
|
||
("keyword", "SingleLineText"),
|
||
]
|
||
SETTINGS_COLS = [
|
||
("title", "SingleLineText"),
|
||
("url", "URL"),
|
||
("enabled", "Checkbox"),
|
||
("notify", "Checkbox"),
|
||
("check_interval_minutes", "Number"),
|
||
("last_checked_at", "DateTime"),
|
||
]
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# HTTP helpers
|
||
# --------------------------------------------------------------------------- #
|
||
def _http(method, url, body=None, headers=None, timeout=30, retries=2):
|
||
"""HTTP 请求。对 Telegram 边缘偶发的 400 做重试。
|
||
|
||
Telegram 的 api.telegram.org 边缘前置(nginx)会偶发对完全合法的请求返回
|
||
400(同 IP、同 token、同 payload 的裸 socket 请求同时却是 200)。命中时
|
||
通知会静默丢失。这里对 400/5xx 做有限重试,间隔递增;仍失败则抛出。
|
||
"""
|
||
h = {"User-Agent": UA}
|
||
if headers:
|
||
h.update(headers)
|
||
data = None
|
||
if body is not None:
|
||
data = json.dumps(body).encode("utf-8")
|
||
h["Content-Type"] = "application/json"
|
||
last = None
|
||
for attempt in range(retries + 1):
|
||
req = urllib.request.Request(url, data=data, method=method, headers=h)
|
||
try:
|
||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||
raw = r.read().decode("utf-8", errors="ignore")
|
||
return r.status, raw
|
||
except urllib.error.HTTPError as e:
|
||
last = e
|
||
# 4xx 里只有 400/408/429 值得重试;其余(如 404/403)立即失败
|
||
if e.code not in (400, 408, 429) and e.code < 500:
|
||
raise
|
||
if attempt < retries:
|
||
time.sleep(0.5 * (attempt + 1))
|
||
if last is not None:
|
||
raise last
|
||
raise RuntimeError("_http: no attempt made")
|
||
|
||
|
||
def _download_image(url, timeout=20):
|
||
"""下载图片到内存 bytes;失败返回 None。"""
|
||
try:
|
||
req = urllib.request.Request(url, headers={"User-Agent": UA})
|
||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||
return r.read()
|
||
except Exception:
|
||
return None
|
||
|
||
|
||
def _send_photo_multipart(chat_id, image_bytes, filename, caption):
|
||
"""用 multipart/form-data 上传本地图片字节发 sendPhoto。
|
||
|
||
逐字段拼装字节(不用 join,避免破坏二进制图片数据)。
|
||
"""
|
||
boundary = "----carousellmonitor" + str(int(time.time() * 1000)) + "boundary"
|
||
CRLF = b"\r\n"
|
||
parts = []
|
||
|
||
def field(name, value):
|
||
p = ("--" + boundary).encode("utf-8") + CRLF
|
||
p += ("Content-Disposition: form-data; name=\"" + name + "\"").encode("utf-8") + CRLF
|
||
p += CRLF
|
||
p += value.encode("utf-8") + CRLF
|
||
return p
|
||
|
||
def file_field(name, filename, data, content_type):
|
||
p = ("--" + boundary).encode("utf-8") + CRLF
|
||
p += ("Content-Disposition: form-data; name=\"" + name +
|
||
"\"; filename=\"" + filename + "\"").encode("utf-8") + CRLF
|
||
p += ("Content-Type: " + content_type).encode("utf-8") + CRLF
|
||
p += CRLF
|
||
p += data + CRLF
|
||
return p
|
||
|
||
body = b""
|
||
body += field("chat_id", str(chat_id))
|
||
body += field("caption", caption)
|
||
body += file_field("photo", filename, image_bytes, "image/jpeg")
|
||
body += ("--" + boundary + "--").encode("utf-8") + CRLF
|
||
|
||
# 走 _tg_call 而不是 urllib:只有它能区分「连接阶段就失败」和「已发出但响应丢了」。
|
||
return _tg_call("sendPhoto", body,
|
||
"multipart/form-data; boundary=" + boundary,
|
||
read_timeout=TG_UPLOAD_READ_TIMEOUT)
|
||
|
||
|
||
def _json(status_raw):
|
||
status, raw = status_raw
|
||
return status, (json.loads(raw) if raw else 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},
|
||
timeout=timeout, retries=retries))
|
||
|
||
|
||
def nc_list_all(tid, fields=None, extra_query=""):
|
||
"""分页拉取一张表的全部记录。
|
||
|
||
NocoDB 的 records API 单次最多返回 1000 行,超出部分只存在于后续 page。
|
||
只拉第一页会让新记录(Id 递增、落在尾部)永远读不到 —— 归档照常写库,
|
||
但通知静默失效。这里用 offset 逐页循环,直到某一页不足 limit 行为止。
|
||
|
||
返回 (status, rows);任何一页失败都返回该页的 (status, None)。
|
||
fields: 逗号分隔的列名,省带宽;None 表示全列。
|
||
extra_query: 额外查询串(不带 ? 或 & 前缀),如 "sort=-CreatedAt"。
|
||
"""
|
||
limit, offset, rows = 1000, 0, []
|
||
while True:
|
||
q = f"?limit={limit}&offset={offset}"
|
||
if fields:
|
||
q += f"&fields={fields}"
|
||
if extra_query:
|
||
q += f"&{extra_query}"
|
||
st, j = nc("GET", f"/api/v2/tables/{tid}/records{q}")
|
||
if st != 200:
|
||
return st, None
|
||
lst = j.get("list", [])
|
||
rows.extend(lst)
|
||
if len(lst) < limit:
|
||
return 200, rows
|
||
offset += limit
|
||
|
||
|
||
TG_SENT, TG_ASSUME_SENT, TG_UNSENT = "SENT", "ASSUME_SENT", "UNSENT"
|
||
|
||
|
||
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)。
|
||
"""
|
||
if isinstance(body, str):
|
||
body = body.encode("utf-8") # Content-Length 必须是字节数;http.client 对 str 走 latin-1
|
||
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
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# Schema bootstrap (idempotent)
|
||
# --------------------------------------------------------------------------- #
|
||
def _ensure_table(title, cols):
|
||
st, tables = nc("GET", f"/api/v2/meta/bases/{NOCODB_BASE_ID}/tables")
|
||
if st != 200:
|
||
raise RuntimeError(f"list tables failed: {tables}")
|
||
tid = None
|
||
for t in tables.get("list", []):
|
||
if t.get("title") == title:
|
||
tid = t["id"]
|
||
if tid is None:
|
||
# NocoDB requires >=1 column inline on create; seed with the first.
|
||
st, out = nc("POST", f"/api/v2/meta/bases/{NOCODB_BASE_ID}/tables",
|
||
{"title": title, "table_name": title, "type": "table",
|
||
"columns": [{"title": cols[0][0], "uidt": cols[0][1]}]})
|
||
if st != 200:
|
||
raise RuntimeError(f"create table {title} failed: {out}")
|
||
tid = out["id"]
|
||
|
||
def _columns_by_title():
|
||
st, meta = nc("GET", f"/api/v2/meta/tables/{tid}")
|
||
return {c.get("title"): c for c in meta.get("columns", [])}
|
||
|
||
existing = _columns_by_title()
|
||
for (ctitle, uidt) in cols:
|
||
if ctitle in existing:
|
||
continue
|
||
st, out = nc("POST", f"/api/v2/meta/tables/{tid}/columns",
|
||
{"title": ctitle, "uidt": uidt})
|
||
if st != 200:
|
||
raise RuntimeError(f"add column {ctitle} failed: {out}")
|
||
|
||
# SingleSelect options. Re-read meta for authoritative column ids: POST
|
||
# /columns returns the *table* object, not the column id.
|
||
existing = _columns_by_title()
|
||
for (ctitle, uidt) in cols:
|
||
if uidt != "SingleSelect" or ctitle not in existing:
|
||
continue
|
||
col = existing[ctitle]
|
||
opts = col.get("colOptions", {}).get("options") or []
|
||
if len(opts) >= len(CONDITIONS):
|
||
continue
|
||
opt_list = [{"title": c, "order": i + 1, "color": None}
|
||
for i, c in enumerate(CONDITIONS)]
|
||
st, out = nc("PATCH", f"/api/v2/meta/columns/{col['id']}",
|
||
{"colOptions": {"options": opt_list},
|
||
"dtxp": ",".join(CONDITIONS)})
|
||
if st != 200:
|
||
raise RuntimeError(f"patch SingleSelect {ctitle} failed: {out}")
|
||
|
||
return tid
|
||
|
||
|
||
def bootstrap():
|
||
listings_tid = _ensure_table("Listings", LISTINGS_COLS)
|
||
settings_tid = _ensure_table("Settings", SETTINGS_COLS)
|
||
ignored_sellers_tid = _ensure_table("IgnoredSellers", IGNORED_SELLERS_COLS)
|
||
ignored_keywords_tid = _ensure_table("IgnoredKeywords", IGNORED_KEYWORDS_COLS)
|
||
kw_fk_col = _ensure_keyword_watch_link(ignored_keywords_tid, settings_tid)
|
||
return (listings_tid, settings_tid, ignored_sellers_tid,
|
||
ignored_keywords_tid, kw_fk_col)
|
||
|
||
def _ensure_keyword_watch_link(kw_tid, settings_tid):
|
||
"""IgnoredKeywords.watch: LinkToAnotherRecord (bt) -> Settings。
|
||
|
||
只维护 watch Link 列(UI 下拉选词条)。search_url 列已废弃:
|
||
运行时经 watch 链接 + Settings.url 解析,无需冗余列。
|
||
NocoDB 2026.08 的建列 API:uidt="LinkToAnotherRecord",顶层
|
||
parentId/childId/type;幂等,旧版遗留的 search_url(URL 或 Lookup 型)
|
||
会被删除。
|
||
"""
|
||
|
||
def _kw_meta():
|
||
st, m = nc("GET", f"/api/v2/meta/tables/{kw_tid}")
|
||
if st != 200:
|
||
raise RuntimeError(f"read IgnoredKeywords meta failed: {m}")
|
||
return m
|
||
|
||
m = _kw_meta()
|
||
cols = {c.get("title"): c for c in m.get("columns", [])}
|
||
|
||
# 1. watch: LinkToAnotherRecord -> Settings
|
||
link_col = None
|
||
if "watch" in cols:
|
||
if cols["watch"].get("uidt") != "LinkToAnotherRecord":
|
||
nc("DELETE", f"/api/v2/meta/columns/{cols['watch']['id']}")
|
||
else:
|
||
link_col = cols["watch"]
|
||
|
||
if link_col is None:
|
||
st, out = nc("POST", f"/api/v2/meta/tables/{kw_tid}/columns",
|
||
{"title": "watch", "uidt": "LinkToAnotherRecord",
|
||
"parentId": settings_tid, "childId": kw_tid,
|
||
"type": "bt", "colOptions": {}})
|
||
if st != 200:
|
||
raise RuntimeError(f"create watch link failed: {out}")
|
||
m = _kw_meta()
|
||
cols = {c.get("title"): c for c in m.get("columns", [])}
|
||
link_col = cols.get("watch")
|
||
|
||
if link_col is None:
|
||
raise RuntimeError("watch link column missing after create")
|
||
|
||
# 2. drop legacy search_url column (URL type or Lookup) — no longer used
|
||
if "search_url" in cols:
|
||
nc("DELETE", f"/api/v2/meta/columns/{cols['search_url']['id']}")
|
||
|
||
|
||
# 3. 找到物理外键列(如 nc_xxx___Settings_id),作为读取 watch 关联的稳定路径:
|
||
# records API 里它返回纯数字 Id,而 watch 列返回对象,形状不保证。
|
||
fk_col = None
|
||
m2 = _kw_meta()
|
||
for c in m2.get("columns", []):
|
||
if c.get("uidt") == "ForeignKey" and c.get("title") != "Id":
|
||
fk_col = c.get("title")
|
||
break
|
||
return fk_col
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# Carousell extraction
|
||
# --------------------------------------------------------------------------- #
|
||
def fetch_listings(search_url):
|
||
st, html = _http("GET", search_url)
|
||
if st != 200:
|
||
raise RuntimeError(f"carousell fetch HTTP {st}")
|
||
blobs = re.findall(r'<script type="application/json">(.*?)</script>',
|
||
html, re.S)
|
||
if not blobs:
|
||
raise RuntimeError("no application/json state found (blocked/ratelimited?)")
|
||
state = json.loads(max(blobs, key=len))
|
||
# listingCards 会在 Carousell 软限流/挑战页时是 null(HTTP 仍是 200)。
|
||
# 不加判断会抛 TypeError: 'NoneType' object is not iterable,把整个 tick
|
||
# 拖垮 → health ok:false → 容器 unhealthy。这里转成清晰的可重试错误。
|
||
sl = state.get("SearchListing") or {}
|
||
cards = sl.get("listingCards")
|
||
if cards is None:
|
||
err = sl.get("error")
|
||
raise RuntimeError(
|
||
f"listingCards null (soft-block/ratelimit? error={err!r})")
|
||
out = []
|
||
for c in cards:
|
||
try:
|
||
lid = int(c["listingID"])
|
||
# 广告卡片:listingID=0(title 常为 ap_promo_*),跳过不归档
|
||
if lid == 0:
|
||
continue
|
||
# 上架时间优先取 time_created;被顶置(bump)的商品只提供
|
||
# active_bump 时间戳,fallback 到它。两者结构相同(timestampContent)。
|
||
ts = None
|
||
for comp in ("time_created", "active_bump"):
|
||
for item in c.get("aboveFold", []):
|
||
if item.get("component") == comp:
|
||
tc = item.get("timestampContent") or {}
|
||
sec = tc.get("seconds") or {}
|
||
ts = sec.get("low")
|
||
break
|
||
if ts:
|
||
break
|
||
bf = c.get("belowFold", [])
|
||
title = next((i["stringContent"] for i in bf
|
||
if i.get("component") == "header_1"), "")
|
||
price_raw = next((i["stringContent"] for i in bf
|
||
if i.get("component") == "header_2"), "")
|
||
paras = [i.get("stringContent", "").strip() for i in bf
|
||
if i.get("component") == "paragraph"]
|
||
# 从所有 paragraph 里找第一个匹配的 condition 值(忽略 Size: 等噪声)
|
||
cond = ""
|
||
for p in paras:
|
||
key = p.lower()
|
||
if key in CONDITION_MAP:
|
||
cond = CONDITION_MAP[key]
|
||
break
|
||
thumb = strip_thumbnail_suffix(c.get("thumbnailURL", ""))
|
||
seller = (c.get("seller") or {}).get("username", "")
|
||
out.append({
|
||
"listing_id": lid,
|
||
"title": title,
|
||
"price": price_raw,
|
||
"condition": cond,
|
||
"thumbnail": thumb,
|
||
"seller": seller,
|
||
"ts": ts,
|
||
})
|
||
except (KeyError, TypeError, ValueError):
|
||
continue
|
||
return out
|
||
|
||
|
||
def parse_price(s):
|
||
if not s:
|
||
return None
|
||
t = re.sub(r"[^0-9.]", "", s)
|
||
if not t:
|
||
return None
|
||
try:
|
||
return round(float(t), 2)
|
||
except ValueError:
|
||
return None
|
||
|
||
|
||
def mimetype_for(url):
|
||
p = url.lower()
|
||
if ".png" in p:
|
||
return "image/png"
|
||
if ".webp" in p:
|
||
return "image/webp"
|
||
if ".gif" in p:
|
||
return "image/gif"
|
||
return "image/jpeg"
|
||
|
||
|
||
def iso_now():
|
||
# UTC: NocoDB parses naive datetimes as UTC.
|
||
return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
|
||
|
||
|
||
def iso_from_epoch(epoch):
|
||
if not epoch:
|
||
return None
|
||
return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(epoch))
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# NocoDB row IO
|
||
# --------------------------------------------------------------------------- #
|
||
def load_seen(listings_tid):
|
||
seen = set()
|
||
st, rows = nc_list_all(listings_tid, fields="product_url")
|
||
if st != 200:
|
||
raise RuntimeError(f"load seen failed: HTTP {st}")
|
||
for r in rows:
|
||
if r.get("product_url"):
|
||
seen.add(r["product_url"])
|
||
return seen
|
||
|
||
|
||
def load_ignored_sellers(ignored_sellers_tid):
|
||
"""从 IgnoredSellers 表读取被忽略的 seller_name 集合。"""
|
||
ignored = set()
|
||
st, rows = nc_list_all(ignored_sellers_tid, fields="seller_name")
|
||
if st != 200:
|
||
raise RuntimeError(f"load ignored sellers failed: HTTP {st}")
|
||
for r in rows:
|
||
name = (r.get("seller_name") or "").strip()
|
||
if name:
|
||
ignored.add(name)
|
||
return ignored
|
||
|
||
|
||
def load_ignored_keywords(ignored_keywords_tid, settings_tid, kw_fk_col=None):
|
||
"""从 IgnoredKeywords 表读取忽略关键词,返回 {search_url: {小写关键词}}。
|
||
|
||
关键词按 watch 分组:watch 是 Link 列(指向 Settings 记录)。这里优先读
|
||
物理外键列 kw_fk_col(如 nc_xxx___Settings_id,records API 返回纯数字),
|
||
该列由 bootstrap 从表 meta 解析出来;拿不到时退回 watch 列对象。
|
||
得到 watch 的 Settings 行 Id 后,一次拉 Settings 表把 Id -> url 建索引。
|
||
匹配时大小写不敏感。
|
||
"""
|
||
ignored = {}
|
||
st, rows = nc_list_all(ignored_keywords_tid)
|
||
if st != 200:
|
||
raise RuntimeError(f"load ignored keywords failed: HTTP {st}")
|
||
|
||
# 先收集 watch 链接的 Settings 行 Id -> 关键词集合
|
||
by_watch_id = {} # settings row Id -> set(keywords lower)
|
||
for r in rows:
|
||
kw = (r.get("keyword") or "").strip().lower()
|
||
if not kw:
|
||
continue
|
||
sid = r.get(kw_fk_col) if kw_fk_col else None
|
||
if sid is None:
|
||
# 兜底:从 watch Link 列对象(或数组)里取 Id
|
||
watch = r.get("watch") or {}
|
||
if isinstance(watch, list):
|
||
watch = watch[0] if watch else {}
|
||
sid = watch.get("Id") if isinstance(watch, dict) else None
|
||
if sid is None:
|
||
continue
|
||
by_watch_id.setdefault(sid, set()).add(kw)
|
||
|
||
if not by_watch_id:
|
||
return ignored
|
||
|
||
# 一次拉 Settings,把 Id -> url 解析出来
|
||
st, srows = nc_list_all(settings_tid, fields="Id,url")
|
||
if st != 200:
|
||
raise RuntimeError(f"load settings for keywords failed: HTTP {st}")
|
||
url_by_id = {r.get("Id"): (r.get("url") or "").strip()
|
||
for r in srows}
|
||
|
||
for sid, kws in by_watch_id.items():
|
||
url = url_by_id.get(sid)
|
||
if url:
|
||
ignored[url] = kws
|
||
return ignored
|
||
|
||
def title_matches_keyword(title, ignored_keywords):
|
||
"""标题命中任一忽略关键词(大小写不敏感的子串匹配)则返回 True。"""
|
||
if not title or not ignored_keywords:
|
||
return False
|
||
t = title.lower()
|
||
return any(kw in t for kw in ignored_keywords)
|
||
|
||
|
||
def load_watches(settings_tid):
|
||
st, rows = nc_list_all(settings_tid)
|
||
if st != 200:
|
||
raise RuntimeError(f"load watches failed: HTTP {st}")
|
||
watches = []
|
||
for r in rows:
|
||
if r.get("enabled"):
|
||
watches.append(r)
|
||
return watches
|
||
|
||
|
||
def insert_listings(listings_tid, rows):
|
||
if not rows:
|
||
return
|
||
st, out = nc("POST", f"/api/v2/tables/{listings_tid}/records", rows)
|
||
if st != 200:
|
||
raise RuntimeError(f"insert listings failed: {out}")
|
||
|
||
|
||
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):
|
||
row = {
|
||
"product_url": PRODUCT_URL_TMPL.format(listing_id=l["listing_id"]),
|
||
"title": l["title"],
|
||
"image_url": l["thumbnail"],
|
||
"image": json.dumps([{"path": l["thumbnail"],
|
||
"mimetype": mimetype_for(l["thumbnail"]),
|
||
"title": f"{l['listing_id']}.jpg"}]),
|
||
"seller_name": l["seller"],
|
||
"seller_url": SELLER_URL_TMPL.format(username=l["seller"]),
|
||
"search_title": watch.get("title", ""),
|
||
"search_url": watch.get("url", ""),
|
||
"first_seen_at": iso_now(),
|
||
"notified": notified,
|
||
"skip_notify": False,
|
||
}
|
||
price = parse_price(l["price"])
|
||
if price is not None:
|
||
row["price"] = price
|
||
if l["condition"]:
|
||
row["condition"] = l["condition"]
|
||
listed = iso_from_epoch(l["ts"])
|
||
if listed:
|
||
row["listed_at"] = listed
|
||
return row
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# Telegram
|
||
# --------------------------------------------------------------------------- #
|
||
def _tg_send(method, payload):
|
||
"""发一条消息。返回 True = 已投递或疑已投递(不可再发)。"""
|
||
if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID:
|
||
return False
|
||
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})
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 通知幂等账本(防重复发送)
|
||
# --------------------------------------------------------------------------- #
|
||
_MEM_LEDGER = None
|
||
|
||
|
||
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 ""
|
||
condition = rec.get("condition") or ""
|
||
seller = rec.get("seller_name") or ""
|
||
product_url = rec.get("product_url") or ""
|
||
caption_lines = [f"🛒 {title}"]
|
||
if price:
|
||
caption_lines.append(f"💰 {price}")
|
||
if condition:
|
||
caption_lines.append(f"📦 {condition}")
|
||
if seller:
|
||
caption_lines.append(f"👤 {seller}")
|
||
if product_url:
|
||
caption_lines.append(product_url)
|
||
caption = "\n".join(caption_lines)
|
||
thumb = rec.get("image_url") or ""
|
||
|
||
if thumb:
|
||
# 方案1:本地下载图后 multipart 上传。下载失败 = 确定没发,可安全降级。
|
||
img_bytes = _download_image(thumb)
|
||
if img_bytes:
|
||
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
|
||
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):
|
||
"""兼容旧调用:把一组 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 末尾统一发通知,返回本轮统计。
|
||
|
||
三重防重(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 次慢盘写事务。
|
||
"""
|
||
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:
|
||
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)
|
||
|
||
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:
|
||
stats["patch_ok"] = False
|
||
return stats
|
||
pending = [r for r in rows if not r.get("notified")]
|
||
if not pending:
|
||
return stats
|
||
|
||
ledger = load_ledger()
|
||
# 这些 key 在 NocoDB 里仍是 notified=false —— 账本哪怕过期也不许淘汰它们
|
||
protected = set()
|
||
for r in pending:
|
||
protected.update(ledger_keys(r))
|
||
|
||
batch = []
|
||
|
||
def flush(force=False):
|
||
"""写回标记。失败后本轮不再自动重试 —— 否则第 10 条失败后,之后每一条都会
|
||
再触发一次 60s 超时的 PATCH,一轮几十次能把容器拖到被 HEALTHCHECK 杀掉。
|
||
轮末用 force=True 再赌一次(只此一次)。"""
|
||
if not batch or (not stats["patch_ok"] and not force):
|
||
return
|
||
if patch_listings(listings_tid, batch):
|
||
del batch[:]
|
||
else:
|
||
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):
|
||
# 不入账本:账本只记录「真的发到 Telegram 的」。批写失败时下一轮
|
||
# 会重新走这条分支(依旧不发),顺带把 skip_notify 一起补上。
|
||
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):
|
||
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):
|
||
# 顺序:先记账本(内存)→ 再排入 batch → 最后落快照。这样快照失败
|
||
# 也不会丢掉「这条已经发出去了」这个事实。
|
||
now_ts = time.time()
|
||
for k in keys:
|
||
ledger[k] = now_ts
|
||
batch.append({"Id": rid, "notified": True})
|
||
stats["sent"] += 1
|
||
try:
|
||
save_ledger(ledger, protected) # 无 fsync 快照,毫秒级
|
||
except Exception as e:
|
||
sys.stderr.write(f"ledger snapshot failed: {e}\n")
|
||
if len(batch) >= 10:
|
||
flush()
|
||
time.sleep(SEND_INTERVAL_SECONDS)
|
||
finally:
|
||
# 轮末:账本带 fsync + .bak 落盘,剩余标记一次批量 PATCH。
|
||
# 两者互相隔离:账本写失败也绝不能跳过 DB 写回。
|
||
try:
|
||
save_ledger(ledger, protected, durable=True)
|
||
except Exception as e:
|
||
sys.stderr.write(f"ledger durable save failed: {e}\n")
|
||
flush(force=True)
|
||
|
||
return stats
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# Health
|
||
# --------------------------------------------------------------------------- #
|
||
def write_health(ok, error, extra=None):
|
||
os.makedirs(DATA_DIR, exist_ok=True)
|
||
h = {"last_run_epoch": int(time.time()), "ok": ok, "error": error or ""}
|
||
if extra:
|
||
h.update(extra)
|
||
tmp = os.path.join(DATA_DIR, "health.json.tmp")
|
||
with open(tmp, "w", encoding="utf-8") as f:
|
||
json.dump(h, f)
|
||
os.replace(tmp, os.path.join(DATA_DIR, "health.json"))
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# Error alerting (Telegram)
|
||
# --------------------------------------------------------------------------- #
|
||
ALERT_STATE_PATH = os.path.join(DATA_DIR, "alert_state.json")
|
||
|
||
|
||
def _load_alert_state():
|
||
try:
|
||
with open(ALERT_STATE_PATH, encoding="utf-8") as f:
|
||
return json.load(f)
|
||
except Exception:
|
||
return {"fail_streak": 0, "alerted": False}
|
||
|
||
|
||
def _save_alert_state(st):
|
||
try:
|
||
os.makedirs(DATA_DIR, exist_ok=True)
|
||
tmp = ALERT_STATE_PATH + ".tmp"
|
||
with open(tmp, "w", encoding="utf-8") as f:
|
||
json.dump(st, f)
|
||
os.replace(tmp, ALERT_STATE_PATH)
|
||
except Exception as e:
|
||
sys.stderr.write(f"alert state write failed: {e}\n")
|
||
|
||
|
||
def alert_on_health(ok, err):
|
||
"""故障时发 Telegram 告警;恢复时发一条恢复通知。
|
||
|
||
连续失败 ERROR_ALERT_AFTER 次才发(去抖),避免偶发单次失败刷屏;
|
||
只在「进入故障」和「恢复」两个边沿各发一条,故障持续期间不重复发。
|
||
告警本身失败绝不影响主循环(全部异常吞掉并写 stderr)。
|
||
"""
|
||
try:
|
||
st = _load_alert_state()
|
||
if not ok:
|
||
st["fail_streak"] = int(st.get("fail_streak", 0)) + 1
|
||
if (st["fail_streak"] >= ERROR_ALERT_AFTER
|
||
and not st.get("alerted")):
|
||
msg = (f"🚨 carousell-monitor 故障\n"
|
||
f"连续失败 {st['fail_streak']} 次\n"
|
||
f"错误: {err or '(none)'}\n"
|
||
f"容器将标记为 unhealthy")
|
||
if tg("sendMessage", {"chat_id": TELEGRAM_CHAT_ID,
|
||
"text": msg})[0] == 200:
|
||
st["alerted"] = True
|
||
st["last_error"] = err or ""
|
||
_save_alert_state(st)
|
||
return
|
||
# ok == True
|
||
if st.get("alerted"):
|
||
msg = ("✅ carousell-monitor 已恢复\n"
|
||
f"故障持续 {st.get('fail_streak', 0)} 个 tick\n"
|
||
f"上次错误: {st.get('last_error') or '(none)'}")
|
||
tg("sendMessage", {"chat_id": TELEGRAM_CHAT_ID, "text": msg})
|
||
_save_alert_state({"fail_streak": 0, "alerted": False})
|
||
except Exception as e:
|
||
sys.stderr.write(f"alert_on_health failed: {e}\n")
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# Main loop
|
||
# --------------------------------------------------------------------------- #
|
||
def run_tick(listings_tid, settings_tid, ignored_sellers_tid, ignored_keywords_tid,
|
||
kw_fk_col, seen, last_run):
|
||
failures = []
|
||
new_total = 0
|
||
checked_ids = []
|
||
watches = load_watches(settings_tid)
|
||
now = time.time()
|
||
|
||
for w in watches:
|
||
wid = w.get("Id")
|
||
interval_min = w.get("check_interval_minutes") or DEFAULT_INTERVAL_MIN
|
||
interval_sec = max(int(interval_min), 1) * 60
|
||
if wid in last_run and (now - last_run[wid]) < interval_sec:
|
||
continue
|
||
|
||
try:
|
||
listings = fetch_listings(w.get("url", ""))
|
||
except Exception as e:
|
||
failures.append(f"{w.get('title')}: {e}")
|
||
# still advance so a hard-failing watch doesn't hammer every tick
|
||
last_run[wid] = now
|
||
time.sleep(FETCH_GAP_SECONDS)
|
||
continue
|
||
|
||
first_seed = not w.get("last_checked_at")
|
||
fresh = [l for l in listings
|
||
if PRODUCT_URL_TMPL.format(listing_id=l["listing_id"]) not in seen]
|
||
|
||
# 首次 seed: 静默归档 (notified=True);后续新商品: 待发 (notified=False)
|
||
rows = [build_row(l, w, notified=first_seed) for l in fresh]
|
||
if rows:
|
||
insert_listings(listings_tid, rows)
|
||
for l in fresh:
|
||
seen.add(PRODUCT_URL_TMPL.format(listing_id=l["listing_id"]))
|
||
|
||
new_total += len(fresh)
|
||
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)
|
||
|
||
# 归档完成后,统一发送待通知的记录(解耦:归档成功才通知)
|
||
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 = 任何失败都算。
|
||
n = len(watches)
|
||
ratio = (len(failures) / n) if n else 0.0
|
||
ok = ratio < FAILURE_RATIO_THRESHOLD if FAILURE_RATIO_THRESHOLD > 0 else True
|
||
err = "; ".join(failures) if failures else ""
|
||
if failures and ok:
|
||
err = f"[partial {len(failures)}/{n}] " + err
|
||
return ok, err, {
|
||
"watch_count": n, "new_this_tick": new_total,
|
||
"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():
|
||
if not NOCODB_TOKEN or not NOCODB_BASE_ID:
|
||
missing = ", ".join(n for n, v in (("NOCODB_TOKEN", NOCODB_TOKEN),
|
||
("NOCODB_BASE_ID", NOCODB_BASE_ID))
|
||
if not v)
|
||
sys.stderr.write(f"{missing} not set\n")
|
||
write_health(False, f"{missing} not set")
|
||
sys.exit(2)
|
||
|
||
(listings_tid, settings_tid, ignored_sellers_tid, ignored_keywords_tid,
|
||
kw_fk_col) = bootstrap()
|
||
seen = load_seen(listings_tid)
|
||
last_run = {}
|
||
|
||
sys.stderr.write(f"ready: listings={listings_tid} settings={settings_tid} "
|
||
f"ignored_sellers={ignored_sellers_tid} "
|
||
f"ignored_keywords={ignored_keywords_tid} seen={len(seen)}\n")
|
||
|
||
while True:
|
||
try:
|
||
ok, err, extra = run_tick(listings_tid, settings_tid,
|
||
ignored_sellers_tid, ignored_keywords_tid,
|
||
kw_fk_col, seen, last_run)
|
||
except Exception as e:
|
||
ok, err, extra = False, f"tick error: {e}", {}
|
||
write_health(ok, err, extra)
|
||
alert_on_health(ok, err)
|
||
time.sleep(TICK_SECONDS)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|