run_once.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  1. #!/usr/bin/env python
  2. """Run one idempotent real-time CPM control cycle."""
  3. from __future__ import annotations
  4. import argparse
  5. import json
  6. import logging
  7. import time
  8. import uuid
  9. from datetime import datetime, timedelta
  10. from decimal import Decimal, ROUND_HALF_UP
  11. from pathlib import Path
  12. from typing import Any
  13. from zoneinfo import ZoneInfo
  14. from dotenv import load_dotenv
  15. ROOT = Path(__file__).resolve().parent
  16. SHANGHAI = ZoneInfo("Asia/Shanghai")
  17. ACTIVE_STATUS = "AD_STATUS_NORMAL"
  18. SUSPEND_STATUS = "AD_STATUS_SUSPEND"
  19. DECISION_BOOST = "BOOST"
  20. DECISION_RESTORE = "RESTORE"
  21. DECISION_PAUSE = "PAUSE"
  22. DECISION_CUTOFF = "CUTOFF"
  23. DECISION_OFF_HOURS = "OFF_HOURS"
  24. DECISION_WAIT_DATA = "WAIT_DATA"
  25. logger = logging.getLogger("tencent_realtime_control")
  26. def load_environment() -> None:
  27. load_dotenv(ROOT.parent / "auto_put_ad_mini" / ".env", override=False)
  28. load_dotenv(Path.cwd() / ".env", override=False)
  29. def decide(cpm: Decimal, low_cpm: Decimal, high_cpm: Decimal) -> str:
  30. if cpm > high_cpm:
  31. return DECISION_BOOST
  32. if cpm < low_cpm:
  33. return DECISION_PAUSE
  34. return DECISION_RESTORE
  35. def boosted_bid(base_bid_fen: int, ratio: Decimal) -> int:
  36. return int(
  37. (Decimal(base_bid_fen) * ratio).quantize(
  38. Decimal("1"), rounding=ROUND_HALF_UP
  39. )
  40. )
  41. def partition_lag_hours(partition: str, now: datetime) -> float:
  42. try:
  43. partition_time = datetime.strptime(partition[:10], "%Y%m%d%H").replace(
  44. tzinfo=SHANGHAI
  45. )
  46. except (TypeError, ValueError) as exc:
  47. raise ValueError(f"Invalid CPM partition: {partition!r}") from exc
  48. return (now - partition_time).total_seconds() / 3600
  49. def should_refresh_inventory(
  50. daily_state: dict[str, Any],
  51. *,
  52. observed_partition: str,
  53. decision: str,
  54. now: datetime,
  55. refresh_minutes: int,
  56. ) -> bool:
  57. if (
  58. daily_state.get("last_observed_partition") != observed_partition
  59. or daily_state.get("last_decision") != decision
  60. ):
  61. return True
  62. refreshed_at = daily_state.get("last_inventory_refresh_at")
  63. if not refreshed_at:
  64. return True
  65. if refreshed_at.tzinfo is None:
  66. refreshed_at = refreshed_at.replace(tzinfo=SHANGHAI)
  67. return now - refreshed_at >= timedelta(minutes=refresh_minutes)
  68. def target_for_ad(
  69. *,
  70. decision: str,
  71. control_date: Any,
  72. current_status: str,
  73. current_bid: int,
  74. base_bid: int,
  75. boosted_date: Any,
  76. paused_by_strategy: bool,
  77. operator_pause_expired: bool,
  78. bid_up_ratio: Decimal,
  79. ) -> dict[str, Any] | None:
  80. managed_suspend = paused_by_strategy or operator_pause_expired
  81. manual_suspend = current_status != ACTIVE_STATUS and not managed_suspend
  82. target_bid = base_bid
  83. target_status: str | None = None
  84. next_boosted_date = boosted_date
  85. next_paused = False
  86. pause_reason = None
  87. limit_reached = False
  88. defer_to_next_day = False
  89. if manual_suspend:
  90. if decision not in (DECISION_PAUSE, DECISION_CUTOFF):
  91. return None
  92. return {
  93. "target_bid_fen": base_bid,
  94. "target_status": None,
  95. "boosted_date": boosted_date,
  96. "paused_by_strategy": False,
  97. "pause_reason": None,
  98. "boost_limit_reached": False,
  99. "bid_change_needed": current_bid != base_bid,
  100. "status_change_needed": False,
  101. "defer_to_next_day": False,
  102. }
  103. if decision == DECISION_BOOST:
  104. if boosted_date == control_date:
  105. limit_reached = True
  106. raised_bid = boosted_bid(base_bid, bid_up_ratio)
  107. if current_bid == raised_bid:
  108. target_bid = raised_bid
  109. else:
  110. target_bid = boosted_bid(base_bid, bid_up_ratio)
  111. next_boosted_date = control_date
  112. if managed_suspend:
  113. target_status = ACTIVE_STATUS
  114. elif decision == DECISION_RESTORE:
  115. if managed_suspend:
  116. target_status = ACTIVE_STATUS
  117. elif decision == DECISION_PAUSE:
  118. if managed_suspend:
  119. target_status = ACTIVE_STATUS
  120. defer_to_next_day = True
  121. elif decision == DECISION_CUTOFF:
  122. target_status = SUSPEND_STATUS if current_status != SUSPEND_STATUS else None
  123. next_paused = True
  124. pause_reason = "cutoff"
  125. else:
  126. raise ValueError(f"Unsupported decision: {decision}")
  127. return {
  128. "target_bid_fen": target_bid,
  129. "target_status": target_status,
  130. "boosted_date": next_boosted_date,
  131. "paused_by_strategy": next_paused,
  132. "pause_reason": pause_reason,
  133. "boost_limit_reached": limit_reached,
  134. "bid_change_needed": current_bid != target_bid,
  135. "status_change_needed": target_status is not None
  136. and target_status != current_status,
  137. "defer_to_next_day": defer_to_next_day,
  138. }
  139. def write_run_report(payload: dict[str, Any]) -> Path:
  140. output_dir = ROOT / "outputs"
  141. output_dir.mkdir(parents=True, exist_ok=True)
  142. timestamp = datetime.now(SHANGHAI).strftime("%Y%m%d_%H%M%S")
  143. mode = "apply" if payload["apply"] else "dry_run"
  144. path = output_dir / f"control_{mode}_{timestamp}.json"
  145. path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
  146. return path
  147. def execute_inventory_action(
  148. *,
  149. run_id: str,
  150. now: datetime,
  151. decision: str,
  152. observed_partition: str | None,
  153. observed_cpm: Decimal | None,
  154. apply: bool,
  155. accounts: list[dict[str, Any]],
  156. config: Any,
  157. tencent: Any,
  158. test_notification: bool = False,
  159. ) -> dict[str, Any]:
  160. from storage import (
  161. clear_operator_pause,
  162. insert_action_log,
  163. load_ad_states,
  164. upsert_ad_state,
  165. )
  166. from tencent_client import current_bid_fen, resolve_bid_field
  167. results: list[dict[str, Any]] = []
  168. failures = 0
  169. api_updates = 0
  170. for account in accounts:
  171. account_id = int(account["account_id"])
  172. states = load_ad_states(account_id)
  173. try:
  174. ads = tencent.get_ads(account_id)
  175. except Exception as exc:
  176. failures += 1
  177. results.append(
  178. {
  179. "account_id": account_id,
  180. "status": "account_fetch_failed",
  181. "error": str(exc),
  182. }
  183. )
  184. continue
  185. for ad in ads:
  186. adgroup_id = int(ad.get("adgroup_id") or 0)
  187. current_status = str(ad.get("configured_status") or "")
  188. state = states.get(adgroup_id)
  189. paused_by_strategy = bool(
  190. (state or {}).get("paused_by_strategy")
  191. )
  192. operator_pause_mode = str(
  193. (state or {}).get("operator_pause_mode") or ""
  194. )
  195. operator_resume_at = (state or {}).get("operator_resume_at")
  196. if operator_resume_at and operator_resume_at.tzinfo is None:
  197. operator_resume_at = operator_resume_at.replace(tzinfo=SHANGHAI)
  198. operator_manually_opened = bool(
  199. operator_pause_mode and current_status == ACTIVE_STATUS
  200. )
  201. operator_pause_expired = bool(
  202. operator_pause_mode == "UNTIL_NEXT_DELIVERY"
  203. and operator_resume_at
  204. and operator_resume_at <= now
  205. )
  206. operator_pause_active = bool(
  207. operator_pause_mode
  208. and not operator_manually_opened
  209. and not operator_pause_expired
  210. )
  211. if operator_manually_opened and apply:
  212. clear_operator_pause(
  213. account_id,
  214. adgroup_id,
  215. action="OPERATOR_MANUAL_OVERRIDE",
  216. action_at=now,
  217. )
  218. results.append(
  219. {
  220. "account_id": account_id,
  221. "audience_name": account.get("audience_name"),
  222. "adgroup_id": adgroup_id,
  223. "adgroup_name": ad.get("adgroup_name"),
  224. "decision": "OPERATOR_MANUAL_OVERRIDE",
  225. "before_status": current_status,
  226. "target_status": current_status,
  227. "status": "success",
  228. "bid_change_needed": False,
  229. "status_change_needed": False,
  230. }
  231. )
  232. continue
  233. if operator_pause_active:
  234. continue
  235. if (
  236. current_status != ACTIVE_STATUS
  237. and not paused_by_strategy
  238. and not operator_pause_expired
  239. and (
  240. state is None
  241. or decision not in (DECISION_PAUSE, DECISION_CUTOFF)
  242. )
  243. ):
  244. continue
  245. bid_field = (
  246. str(state["bid_field"])
  247. if state
  248. else resolve_bid_field(ad, account.get("bid_scene"))
  249. )
  250. current_bid = current_bid_fen(ad, bid_field)
  251. if current_bid is None or current_bid <= 0:
  252. failures += 1
  253. results.append(
  254. {
  255. "account_id": account_id,
  256. "adgroup_id": adgroup_id,
  257. "status": "invalid_current_bid",
  258. "bid_field": bid_field,
  259. }
  260. )
  261. continue
  262. base_bid = int(state["base_bid_fen"]) if state else current_bid
  263. plan = target_for_ad(
  264. decision=decision,
  265. control_date=now.date(),
  266. current_status=current_status,
  267. current_bid=current_bid,
  268. base_bid=base_bid,
  269. boosted_date=(state or {}).get("boosted_date"),
  270. paused_by_strategy=paused_by_strategy,
  271. operator_pause_expired=operator_pause_expired,
  272. bid_up_ratio=config.bid_up_ratio,
  273. )
  274. if plan is None:
  275. continue
  276. before_begin_date = str(ad.get("begin_date") or "")
  277. target_begin_date = None
  278. begin_date_change_needed = False
  279. if plan["defer_to_next_day"]:
  280. next_day = (now.date() + timedelta(days=1)).isoformat()
  281. target_begin_date = (
  282. before_begin_date
  283. if before_begin_date > next_day
  284. else next_day
  285. )
  286. begin_date_change_needed = before_begin_date != target_begin_date
  287. needs_api = (
  288. plan["bid_change_needed"]
  289. or plan["status_change_needed"]
  290. or begin_date_change_needed
  291. )
  292. execution_status = "planned" if needs_api else "noop"
  293. error = None
  294. if apply and state is None:
  295. upsert_ad_state(
  296. account_id=account_id,
  297. adgroup_id=adgroup_id,
  298. adgroup_name=str(ad.get("adgroup_name") or ""),
  299. bid_field=bid_field,
  300. base_bid_fen=base_bid,
  301. boosted_date=None,
  302. paused_by_strategy=plan["paused_by_strategy"],
  303. pause_reason=plan["pause_reason"],
  304. last_action="REGISTER_BASE",
  305. action_at=now,
  306. )
  307. elif (
  308. apply
  309. and decision in (DECISION_PAUSE, DECISION_CUTOFF)
  310. and plan["paused_by_strategy"]
  311. ):
  312. upsert_ad_state(
  313. account_id=account_id,
  314. adgroup_id=adgroup_id,
  315. adgroup_name=str(ad.get("adgroup_name") or ""),
  316. bid_field=bid_field,
  317. base_bid_fen=base_bid,
  318. boosted_date=(state or {}).get("boosted_date"),
  319. paused_by_strategy=True,
  320. pause_reason=plan["pause_reason"],
  321. last_action=f"{decision}_PENDING",
  322. action_at=now,
  323. )
  324. if apply and needs_api:
  325. try:
  326. if begin_date_change_needed:
  327. tencent.update_ad_begin_dates(
  328. account_id,
  329. [adgroup_id],
  330. str(target_begin_date),
  331. )
  332. if plan["bid_change_needed"] or plan["status_change_needed"]:
  333. tencent.update_ad(
  334. account_id,
  335. adgroup_id,
  336. bid_field=bid_field
  337. if plan["bid_change_needed"]
  338. else None,
  339. target_bid_fen=plan["target_bid_fen"]
  340. if plan["bid_change_needed"]
  341. else None,
  342. target_status=plan["target_status"]
  343. if plan["status_change_needed"]
  344. else None,
  345. )
  346. execution_status = "success"
  347. api_updates += 1
  348. time.sleep(0.15)
  349. except Exception as exc:
  350. execution_status = "failed"
  351. error = str(exc)
  352. failures += 1
  353. result = {
  354. "account_id": account_id,
  355. "audience_name": account.get("audience_name"),
  356. "adgroup_id": adgroup_id,
  357. "adgroup_name": ad.get("adgroup_name"),
  358. "decision": decision,
  359. "bid_field": bid_field,
  360. "base_bid_fen": base_bid,
  361. "before_bid_fen": current_bid,
  362. "target_bid_fen": plan["target_bid_fen"],
  363. "before_status": current_status,
  364. "target_status": plan["target_status"],
  365. "boost_limit_reached": plan["boost_limit_reached"],
  366. "bid_change_needed": plan["bid_change_needed"],
  367. "status_change_needed": plan["status_change_needed"],
  368. "before_begin_date": before_begin_date,
  369. "target_begin_date": target_begin_date,
  370. "begin_date_change_needed": begin_date_change_needed,
  371. "status": execution_status,
  372. "error": error,
  373. }
  374. results.append(result)
  375. if apply and execution_status != "failed":
  376. upsert_ad_state(
  377. account_id=account_id,
  378. adgroup_id=adgroup_id,
  379. adgroup_name=str(ad.get("adgroup_name") or ""),
  380. bid_field=bid_field,
  381. base_bid_fen=base_bid,
  382. boosted_date=plan["boosted_date"],
  383. paused_by_strategy=plan["paused_by_strategy"],
  384. pause_reason=plan["pause_reason"],
  385. last_action=decision,
  386. action_at=now,
  387. )
  388. if operator_pause_expired:
  389. clear_operator_pause(
  390. account_id,
  391. adgroup_id,
  392. action="OPERATOR_DAY_PAUSE_EXPIRED",
  393. action_at=now,
  394. )
  395. if apply and (needs_api or state is None or execution_status == "failed"):
  396. insert_action_log(
  397. {
  398. "run_id": run_id,
  399. "control_date": now.date(),
  400. "observed_partition": observed_partition,
  401. "observed_cpm": observed_cpm,
  402. "decision": decision,
  403. "account_id": account_id,
  404. "adgroup_id": adgroup_id,
  405. "adgroup_name": ad.get("adgroup_name"),
  406. "bid_field": bid_field,
  407. "base_bid_fen": base_bid,
  408. "before_bid_fen": current_bid,
  409. "target_bid_fen": plan["target_bid_fen"],
  410. "before_status": current_status,
  411. "target_status": plan["target_status"],
  412. "apply_mode": True,
  413. "execution_status": execution_status,
  414. "error_message": error,
  415. }
  416. )
  417. notification = {"status": "dry_run" if not apply else "no_actions"}
  418. if apply or test_notification:
  419. from feishu_notifier import send_action_notification
  420. report_actions: dict[int, list[dict[str, Any]]] = {}
  421. expected_statuses = {"success", "failed"} if apply else {"planned"}
  422. for result in results:
  423. if result.get("status") not in expected_statuses:
  424. continue
  425. if not (
  426. result.get("bid_change_needed")
  427. or result.get("begin_date_change_needed")
  428. or (
  429. result.get("decision") in (DECISION_PAUSE, DECISION_CUTOFF)
  430. and result.get("status_change_needed")
  431. )
  432. ):
  433. continue
  434. report_actions.setdefault(int(result["account_id"]), []).append(
  435. result
  436. )
  437. for account_id, account_results in report_actions.items():
  438. try:
  439. metrics = tencent.get_today_ad_metrics(
  440. account_id,
  441. [int(row["adgroup_id"]) for row in account_results],
  442. now.date(),
  443. )
  444. for result in account_results:
  445. ad_metrics = metrics.get(int(result["adgroup_id"]), {})
  446. result["today_cost_fen"] = int(
  447. ad_metrics.get("cost_fen") or 0
  448. )
  449. result["today_impressions"] = int(
  450. ad_metrics.get("impressions") or 0
  451. )
  452. result["today_clicks"] = int(
  453. ad_metrics.get("clicks") or 0
  454. )
  455. except Exception as exc:
  456. logger.warning(
  457. "Failed to fetch today's metrics account=%s: %s",
  458. account_id,
  459. exc,
  460. )
  461. notification = send_action_notification(
  462. run_id=run_id,
  463. now=now,
  464. results=results,
  465. bid_up_ratio=config.bid_up_ratio,
  466. decision=decision,
  467. observed_partition=observed_partition,
  468. observed_cpm=observed_cpm,
  469. test_mode=test_notification,
  470. )
  471. if apply:
  472. try:
  473. from feishu_notifier import (
  474. send_operator_reconciliation_notification,
  475. )
  476. send_operator_reconciliation_notification(results)
  477. except Exception:
  478. logger.exception(
  479. "Failed to notify operator manual override reconciliation"
  480. )
  481. return {
  482. "failures": failures,
  483. "api_updates": api_updates,
  484. "results": results,
  485. "notification": notification,
  486. }
  487. def run_cycle(
  488. *,
  489. now: datetime,
  490. apply: bool,
  491. cpm_override: Decimal | None = None,
  492. force_refresh: bool = False,
  493. test_notification: bool = False,
  494. ) -> dict[str, Any]:
  495. from odps_source import HourlyCpm, build_odps_client, fetch_latest_cpm
  496. from realtime_config import RealtimeControlConfig
  497. from storage import (
  498. advisory_lock,
  499. load_daily_state,
  500. load_realtime_accounts,
  501. save_daily_state,
  502. )
  503. from tencent_client import TencentClient
  504. config = RealtimeControlConfig.from_env()
  505. run_id = str(uuid.uuid4())
  506. payload: dict[str, Any] = {
  507. "run_id": run_id,
  508. "now": now.isoformat(),
  509. "apply": apply,
  510. "decision": None,
  511. "observed_partition": None,
  512. "observed_cpm": None,
  513. "summary": {},
  514. }
  515. with advisory_lock(config.lock_name) as acquired:
  516. if not acquired:
  517. payload["decision"] = "LOCKED_BY_OTHER_WORKER"
  518. return payload
  519. daily_state = load_daily_state(now.date())
  520. accounts = load_realtime_accounts()
  521. if now.hour < config.start_hour:
  522. payload["decision"] = DECISION_OFF_HOURS
  523. return payload
  524. if now.hour >= config.stop_hour:
  525. payload["decision"] = DECISION_CUTOFF
  526. if apply and bool(daily_state.get("cutoff_done")) and not force_refresh:
  527. payload["summary"] = {"status": "cutoff_already_done"}
  528. return payload
  529. execution = execute_inventory_action(
  530. run_id=run_id,
  531. now=now,
  532. decision=DECISION_RESTORE,
  533. observed_partition=None,
  534. observed_cpm=None,
  535. apply=apply,
  536. accounts=accounts,
  537. config=config,
  538. tencent=TencentClient(),
  539. test_notification=test_notification,
  540. )
  541. payload["summary"] = execution
  542. if apply and not execution["failures"]:
  543. save_daily_state(
  544. now.date(),
  545. cutoff_done=True,
  546. last_decision=DECISION_CUTOFF,
  547. last_inventory_refresh_at=now,
  548. last_evaluated_at=now,
  549. )
  550. return payload
  551. if apply and not bool(daily_state.get("morning_recovery_done")):
  552. execution = execute_inventory_action(
  553. run_id=run_id,
  554. now=now,
  555. decision=DECISION_RESTORE,
  556. observed_partition=None,
  557. observed_cpm=None,
  558. apply=True,
  559. accounts=accounts,
  560. config=config,
  561. tencent=TencentClient(),
  562. test_notification=test_notification,
  563. )
  564. payload["decision"] = "MORNING_RECOVERY"
  565. payload["summary"] = execution
  566. if not execution["failures"]:
  567. save_daily_state(
  568. now.date(),
  569. morning_recovery_done=True,
  570. last_inventory_refresh_at=now,
  571. last_evaluated_at=now,
  572. )
  573. else:
  574. return payload
  575. if cpm_override is not None:
  576. signal = HourlyCpm(
  577. partition=f"{now.strftime('%Y%m%d%H')}_override",
  578. hour_of_day=now.hour,
  579. impressions=0,
  580. cpm=float(cpm_override),
  581. )
  582. else:
  583. signal = fetch_latest_cpm(build_odps_client(), now.date())
  584. earliest_signal_hour = max(0, config.start_hour - 1)
  585. if signal is None or signal.hour_of_day < earliest_signal_hour:
  586. payload["decision"] = DECISION_WAIT_DATA
  587. payload["summary"] = {
  588. "reason": (
  589. "No same-day CPM partition at or after "
  590. f"{earliest_signal_hour:02d}:00"
  591. )
  592. }
  593. return payload
  594. observed_cpm = Decimal(str(signal.cpm))
  595. lag_hours = partition_lag_hours(signal.partition, now)
  596. payload.update(
  597. {
  598. "observed_partition": signal.partition,
  599. "observed_cpm": float(observed_cpm),
  600. "impressions": signal.impressions,
  601. "partition_lag_hours": round(lag_hours, 4),
  602. }
  603. )
  604. if lag_hours < 0 or lag_hours > config.max_partition_lag_hours:
  605. payload["decision"] = DECISION_WAIT_DATA
  606. payload["summary"] = {
  607. "reason": (
  608. f"CPM partition lag {lag_hours:.2f}h exceeds allowed "
  609. f"{config.max_partition_lag_hours}h"
  610. )
  611. }
  612. return payload
  613. decision = decide(observed_cpm, config.low_cpm, config.high_cpm)
  614. payload.update(
  615. {
  616. "decision": decision,
  617. }
  618. )
  619. refresh = force_refresh or should_refresh_inventory(
  620. daily_state,
  621. observed_partition=signal.partition,
  622. decision=decision,
  623. now=now,
  624. refresh_minutes=config.inventory_refresh_minutes,
  625. )
  626. if apply and not refresh:
  627. save_daily_state(now.date(), last_evaluated_at=now)
  628. payload["summary"] = {"status": "same_signal_noop"}
  629. return payload
  630. execution = execute_inventory_action(
  631. run_id=run_id,
  632. now=now,
  633. decision=decision,
  634. observed_partition=signal.partition,
  635. observed_cpm=observed_cpm,
  636. apply=apply,
  637. accounts=accounts,
  638. config=config,
  639. tencent=TencentClient(),
  640. test_notification=test_notification,
  641. )
  642. payload["summary"] = execution
  643. if apply and not execution["failures"]:
  644. save_daily_state(
  645. now.date(),
  646. last_observed_partition=signal.partition,
  647. last_observed_cpm=observed_cpm,
  648. last_decision=decision,
  649. last_inventory_refresh_at=now,
  650. last_evaluated_at=now,
  651. )
  652. return payload
  653. def parse_args() -> argparse.Namespace:
  654. parser = argparse.ArgumentParser(description=__doc__)
  655. parser.add_argument(
  656. "--apply",
  657. action="store_true",
  658. help="Execute Tencent updates. Default is dry-run.",
  659. )
  660. parser.add_argument(
  661. "--at",
  662. help="Dry-run only: simulate Shanghai local time, ISO format.",
  663. )
  664. parser.add_argument(
  665. "--cpm-override",
  666. type=Decimal,
  667. help="Dry-run only: override latest CPM to validate decision branches.",
  668. )
  669. parser.add_argument("--force-refresh", action="store_true")
  670. parser.add_argument(
  671. "--test-notification",
  672. action="store_true",
  673. help=(
  674. "Dry-run only: use real inventory and metrics, then send a clearly "
  675. "marked simulated Feishu action sheet."
  676. ),
  677. )
  678. return parser.parse_args()
  679. def main() -> int:
  680. load_environment()
  681. args = parse_args()
  682. if args.apply and (args.at or args.cpm_override is not None):
  683. raise ValueError("--at and --cpm-override are forbidden with --apply")
  684. if args.apply and args.test_notification:
  685. raise ValueError("--test-notification is forbidden with --apply")
  686. now = (
  687. datetime.fromisoformat(args.at).replace(tzinfo=SHANGHAI)
  688. if args.at
  689. else datetime.now(SHANGHAI)
  690. )
  691. payload = run_cycle(
  692. now=now,
  693. apply=args.apply,
  694. cpm_override=args.cpm_override,
  695. force_refresh=args.force_refresh,
  696. test_notification=args.test_notification,
  697. )
  698. report = write_run_report(payload)
  699. compact = {
  700. "decision": payload["decision"],
  701. "observed_partition": payload.get("observed_partition"),
  702. "observed_cpm": payload.get("observed_cpm"),
  703. "apply": payload["apply"],
  704. "api_updates": payload.get("summary", {}).get("api_updates", 0),
  705. "failures": payload.get("summary", {}).get("failures", 0),
  706. "notification": payload.get("summary", {}).get("notification", {}).get(
  707. "status"
  708. ),
  709. "report": str(report),
  710. }
  711. print(json.dumps(compact, ensure_ascii=False))
  712. return 1 if compact["failures"] else 0
  713. if __name__ == "__main__":
  714. logging.basicConfig(
  715. level=logging.INFO,
  716. format="%(asctime)s %(levelname)s %(name)s %(message)s",
  717. )
  718. try:
  719. raise SystemExit(main())
  720. except Exception as exc:
  721. logger.exception("Real-time control failed: %s", exc)
  722. raise SystemExit(1)