storage.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. """MySQL state and audit storage for real-time control."""
  2. from __future__ import annotations
  3. import os
  4. import json
  5. from contextlib import contextmanager
  6. from datetime import date, datetime
  7. from pathlib import Path
  8. from typing import Any, Iterator
  9. import pymysql
  10. import pymysql.cursors
  11. ROOT = Path(__file__).resolve().parent
  12. def connect() -> pymysql.Connection:
  13. required = ["DB_HOST", "DB_USER", "DB_NAME"]
  14. missing = [key for key in required if not os.getenv(key)]
  15. if missing:
  16. raise RuntimeError(f"Missing database environment variables: {', '.join(missing)}")
  17. return pymysql.connect(
  18. host=os.environ["DB_HOST"],
  19. port=int(os.getenv("DB_PORT", "3306")),
  20. user=os.environ["DB_USER"],
  21. password=os.getenv("DB_PASSWORD", ""),
  22. database=os.environ["DB_NAME"],
  23. charset="utf8mb4",
  24. cursorclass=pymysql.cursors.DictCursor,
  25. autocommit=True,
  26. connect_timeout=int(os.getenv("DB_CONNECT_TIMEOUT", "10")),
  27. read_timeout=int(os.getenv("DB_READ_TIMEOUT", "60")),
  28. write_timeout=int(os.getenv("DB_WRITE_TIMEOUT", "60")),
  29. )
  30. def initialize_schema() -> None:
  31. statements = [
  32. statement.strip()
  33. for statement in (ROOT / "schema.sql").read_text(encoding="utf-8").split(";")
  34. if statement.strip()
  35. ]
  36. connection = connect()
  37. try:
  38. with connection.cursor() as cursor:
  39. for statement in statements:
  40. cursor.execute(statement)
  41. cursor.execute(
  42. """
  43. SELECT COLUMN_NAME
  44. FROM information_schema.COLUMNS
  45. WHERE TABLE_SCHEMA=%s
  46. AND TABLE_NAME='realtime_control_ad_state'
  47. """,
  48. (os.environ["DB_NAME"],),
  49. )
  50. existing_columns = {row["COLUMN_NAME"] for row in cursor.fetchall()}
  51. migrations = {
  52. "operator_pause_mode": "VARCHAR(32) DEFAULT NULL",
  53. "operator_resume_at": "DATETIME DEFAULT NULL",
  54. "operator_command_id": "VARCHAR(64) DEFAULT NULL",
  55. "operator_paused_from_status": "VARCHAR(50) DEFAULT NULL",
  56. "operator_paused_at": "DATETIME DEFAULT NULL",
  57. }
  58. for column, definition in migrations.items():
  59. if column not in existing_columns:
  60. cursor.execute(
  61. f"ALTER TABLE realtime_control_ad_state "
  62. f"ADD COLUMN {column} {definition}"
  63. )
  64. cursor.execute(
  65. """
  66. SELECT INDEX_NAME
  67. FROM information_schema.STATISTICS
  68. WHERE TABLE_SCHEMA=%s
  69. AND TABLE_NAME='realtime_control_ad_state'
  70. AND INDEX_NAME='idx_operator_pause'
  71. """,
  72. (os.environ["DB_NAME"],),
  73. )
  74. if not cursor.fetchone():
  75. cursor.execute(
  76. """
  77. CREATE INDEX idx_operator_pause
  78. ON realtime_control_ad_state
  79. (operator_pause_mode, operator_resume_at)
  80. """
  81. )
  82. finally:
  83. connection.close()
  84. @contextmanager
  85. def advisory_lock(lock_name: str) -> Iterator[bool]:
  86. connection = connect()
  87. acquired = False
  88. try:
  89. with connection.cursor() as cursor:
  90. cursor.execute("SELECT GET_LOCK(%s, 0) AS acquired", (lock_name,))
  91. acquired = bool((cursor.fetchone() or {}).get("acquired"))
  92. yield acquired
  93. finally:
  94. if acquired:
  95. try:
  96. with connection.cursor() as cursor:
  97. cursor.execute("SELECT RELEASE_LOCK(%s)", (lock_name,))
  98. except Exception:
  99. pass
  100. connection.close()
  101. def load_enabled_accounts() -> list[dict[str, Any]]:
  102. connection = connect()
  103. try:
  104. with connection.cursor() as cursor:
  105. cursor.execute(
  106. """
  107. SELECT c.account_id, c.audience_name, c.bid_scene
  108. FROM ad_creation_account_config c
  109. JOIN account_whitelist w ON w.account_id = c.account_id
  110. WHERE c.enabled = TRUE
  111. AND w.enabled = TRUE
  112. ORDER BY c.account_id
  113. """
  114. )
  115. return list(cursor.fetchall())
  116. finally:
  117. connection.close()
  118. def load_realtime_accounts() -> list[dict[str, Any]]:
  119. """All historical automation accounts still enabled by the whitelist."""
  120. connection = connect()
  121. try:
  122. with connection.cursor() as cursor:
  123. cursor.execute(
  124. """
  125. SELECT c.account_id, c.audience_name, c.bid_scene
  126. FROM ad_creation_account_config c
  127. JOIN account_whitelist w ON w.account_id = c.account_id
  128. WHERE w.enabled = TRUE
  129. ORDER BY c.account_id
  130. """
  131. )
  132. return list(cursor.fetchall())
  133. finally:
  134. connection.close()
  135. def load_managed_accounts() -> list[dict[str, Any]]:
  136. """Historical automation accounts still allowed by the account whitelist."""
  137. connection = connect()
  138. try:
  139. with connection.cursor() as cursor:
  140. cursor.execute(
  141. """
  142. SELECT c.account_id, c.audience_name, c.bid_scene, c.enabled
  143. FROM ad_creation_account_config c
  144. JOIN account_whitelist w ON w.account_id = c.account_id
  145. WHERE w.enabled = TRUE
  146. ORDER BY c.account_id
  147. """
  148. )
  149. return list(cursor.fetchall())
  150. finally:
  151. connection.close()
  152. def load_daily_state(control_date: date) -> dict[str, Any]:
  153. connection = connect()
  154. try:
  155. with connection.cursor() as cursor:
  156. cursor.execute(
  157. "SELECT * FROM realtime_control_daily_state WHERE control_date=%s",
  158. (control_date,),
  159. )
  160. return cursor.fetchone() or {}
  161. finally:
  162. connection.close()
  163. def save_daily_state(control_date: date, **values: Any) -> None:
  164. allowed = {
  165. "morning_recovery_done",
  166. "cutoff_done",
  167. "last_observed_partition",
  168. "last_observed_cpm",
  169. "last_decision",
  170. "last_inventory_refresh_at",
  171. "last_evaluated_at",
  172. }
  173. unknown = set(values) - allowed
  174. if unknown:
  175. raise ValueError(f"Unsupported daily-state fields: {sorted(unknown)}")
  176. columns = ["control_date", *values]
  177. params = [control_date, *values.values()]
  178. updates = ", ".join(f"{column}=VALUES({column})" for column in values)
  179. placeholders = ", ".join(["%s"] * len(columns))
  180. sql = (
  181. f"INSERT INTO realtime_control_daily_state ({', '.join(columns)}) "
  182. f"VALUES ({placeholders}) ON DUPLICATE KEY UPDATE {updates}"
  183. )
  184. connection = connect()
  185. try:
  186. with connection.cursor() as cursor:
  187. cursor.execute(sql, params)
  188. finally:
  189. connection.close()
  190. def load_ad_states(account_id: int) -> dict[int, dict[str, Any]]:
  191. connection = connect()
  192. try:
  193. with connection.cursor() as cursor:
  194. cursor.execute(
  195. "SELECT * FROM realtime_control_ad_state WHERE account_id=%s",
  196. (account_id,),
  197. )
  198. return {int(row["adgroup_id"]): row for row in cursor.fetchall()}
  199. finally:
  200. connection.close()
  201. def upsert_ad_state(
  202. *,
  203. account_id: int,
  204. adgroup_id: int,
  205. adgroup_name: str,
  206. bid_field: str,
  207. base_bid_fen: int,
  208. boosted_date: date | None,
  209. paused_by_strategy: bool,
  210. pause_reason: str | None,
  211. last_action: str,
  212. action_at: datetime,
  213. ) -> None:
  214. connection = connect()
  215. try:
  216. with connection.cursor() as cursor:
  217. cursor.execute(
  218. """
  219. INSERT INTO realtime_control_ad_state
  220. (account_id, adgroup_id, adgroup_name, bid_field, base_bid_fen,
  221. boosted_date, paused_by_strategy, pause_reason, last_action,
  222. last_action_at, last_seen_at)
  223. VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
  224. ON DUPLICATE KEY UPDATE
  225. adgroup_name=VALUES(adgroup_name),
  226. bid_field=VALUES(bid_field),
  227. boosted_date=VALUES(boosted_date),
  228. paused_by_strategy=VALUES(paused_by_strategy),
  229. pause_reason=VALUES(pause_reason),
  230. last_action=VALUES(last_action),
  231. last_action_at=VALUES(last_action_at),
  232. last_seen_at=VALUES(last_seen_at)
  233. """,
  234. (
  235. account_id,
  236. adgroup_id,
  237. adgroup_name,
  238. bid_field,
  239. base_bid_fen,
  240. boosted_date,
  241. paused_by_strategy,
  242. pause_reason,
  243. last_action,
  244. action_at,
  245. action_at,
  246. ),
  247. )
  248. finally:
  249. connection.close()
  250. def insert_action_log(record: dict[str, Any]) -> None:
  251. columns = [
  252. "run_id",
  253. "control_date",
  254. "observed_partition",
  255. "observed_cpm",
  256. "decision",
  257. "account_id",
  258. "adgroup_id",
  259. "adgroup_name",
  260. "bid_field",
  261. "base_bid_fen",
  262. "before_bid_fen",
  263. "target_bid_fen",
  264. "before_status",
  265. "target_status",
  266. "apply_mode",
  267. "execution_status",
  268. "error_message",
  269. ]
  270. connection = connect()
  271. try:
  272. with connection.cursor() as cursor:
  273. cursor.execute(
  274. f"INSERT INTO realtime_control_action_log ({', '.join(columns)}) "
  275. f"VALUES ({', '.join(['%s'] * len(columns))})",
  276. [record.get(column) for column in columns],
  277. )
  278. finally:
  279. connection.close()
  280. def create_operator_command(record: dict[str, Any]) -> dict[str, Any]:
  281. connection = connect()
  282. try:
  283. with connection.cursor() as cursor:
  284. try:
  285. cursor.execute(
  286. """
  287. INSERT INTO operator_command
  288. (command_id, source_message_id, chat_id, sender_open_id,
  289. sender_name, action, scope_type, target_account_ids,
  290. status, preview_account_count, preview_ad_count, expires_at)
  291. VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
  292. """,
  293. (
  294. record["command_id"],
  295. record["source_message_id"],
  296. record["chat_id"],
  297. record["sender_open_id"],
  298. record.get("sender_name"),
  299. record["action"],
  300. record["scope_type"],
  301. json.dumps(record["target_account_ids"]),
  302. record["status"],
  303. record.get("preview_account_count", 0),
  304. record.get("preview_ad_count", 0),
  305. record.get("expires_at"),
  306. ),
  307. )
  308. except pymysql.err.IntegrityError:
  309. cursor.execute(
  310. "SELECT * FROM operator_command WHERE source_message_id=%s",
  311. (record["source_message_id"],),
  312. )
  313. existing = cursor.fetchone()
  314. if existing:
  315. existing["target_account_ids"] = json.loads(
  316. existing.get("target_account_ids") or "[]"
  317. )
  318. return existing
  319. raise
  320. return load_operator_command(record["command_id"]) or {}
  321. finally:
  322. connection.close()
  323. def load_operator_command(command_id: str) -> dict[str, Any] | None:
  324. connection = connect()
  325. try:
  326. with connection.cursor() as cursor:
  327. cursor.execute(
  328. "SELECT * FROM operator_command WHERE command_id=%s",
  329. (command_id,),
  330. )
  331. row = cursor.fetchone()
  332. if row:
  333. row["target_account_ids"] = json.loads(
  334. row.get("target_account_ids") or "[]"
  335. )
  336. return row
  337. finally:
  338. connection.close()
  339. def update_operator_command(command_id: str, status: str, **values: Any) -> None:
  340. allowed = {"confirmed_at", "executed_at", "error_message"}
  341. unknown = set(values) - allowed
  342. if unknown:
  343. raise ValueError(f"Unsupported operator-command fields: {sorted(unknown)}")
  344. assignments = ["status=%s"]
  345. params: list[Any] = [status]
  346. for column, value in values.items():
  347. assignments.append(f"{column}=%s")
  348. params.append(value)
  349. params.append(command_id)
  350. connection = connect()
  351. try:
  352. with connection.cursor() as cursor:
  353. cursor.execute(
  354. f"UPDATE operator_command SET {', '.join(assignments)} "
  355. "WHERE command_id=%s",
  356. params,
  357. )
  358. finally:
  359. connection.close()
  360. def transition_operator_command(
  361. command_id: str,
  362. *,
  363. expected_statuses: set[str],
  364. target_status: str,
  365. **values: Any,
  366. ) -> bool:
  367. allowed = {"confirmed_at", "executed_at", "error_message"}
  368. unknown = set(values) - allowed
  369. if unknown:
  370. raise ValueError(f"Unsupported operator-command fields: {sorted(unknown)}")
  371. if not expected_statuses:
  372. raise ValueError("expected_statuses must not be empty")
  373. assignments = ["status=%s"]
  374. params: list[Any] = [target_status]
  375. for column, value in values.items():
  376. assignments.append(f"{column}=%s")
  377. params.append(value)
  378. placeholders = ", ".join(["%s"] * len(expected_statuses))
  379. params.extend([command_id, *sorted(expected_statuses)])
  380. connection = connect()
  381. try:
  382. with connection.cursor() as cursor:
  383. affected = cursor.execute(
  384. f"""
  385. UPDATE operator_command
  386. SET {', '.join(assignments)}
  387. WHERE command_id=%s
  388. AND status IN ({placeholders})
  389. """,
  390. params,
  391. )
  392. return affected == 1
  393. finally:
  394. connection.close()
  395. def insert_operator_command_item(record: dict[str, Any]) -> None:
  396. columns = [
  397. "command_id",
  398. "account_id",
  399. "audience_name",
  400. "adgroup_id",
  401. "adgroup_name",
  402. "before_status",
  403. "target_status",
  404. "readback_status",
  405. "execution_status",
  406. "error_message",
  407. ]
  408. connection = connect()
  409. try:
  410. with connection.cursor() as cursor:
  411. cursor.execute(
  412. f"INSERT INTO operator_command_item ({', '.join(columns)}) "
  413. f"VALUES ({', '.join(['%s'] * len(columns))})",
  414. [record.get(column) for column in columns],
  415. )
  416. finally:
  417. connection.close()
  418. def set_operator_pause(
  419. *,
  420. account_id: int,
  421. adgroup_id: int,
  422. mode: str,
  423. resume_at: datetime | None,
  424. command_id: str,
  425. paused_from_status: str,
  426. paused_at: datetime,
  427. ) -> None:
  428. connection = connect()
  429. try:
  430. with connection.cursor() as cursor:
  431. cursor.execute(
  432. """
  433. UPDATE realtime_control_ad_state
  434. SET operator_pause_mode=%s,
  435. operator_resume_at=%s,
  436. operator_command_id=%s,
  437. operator_paused_from_status=%s,
  438. operator_paused_at=%s,
  439. last_action='OPERATOR_PAUSE',
  440. last_action_at=%s,
  441. last_seen_at=%s
  442. WHERE account_id=%s AND adgroup_id=%s
  443. """,
  444. (
  445. mode,
  446. resume_at,
  447. command_id,
  448. paused_from_status,
  449. paused_at,
  450. paused_at,
  451. paused_at,
  452. account_id,
  453. adgroup_id,
  454. ),
  455. )
  456. finally:
  457. connection.close()
  458. def clear_operator_pause(
  459. account_id: int,
  460. adgroup_id: int,
  461. *,
  462. action: str,
  463. action_at: datetime,
  464. ) -> None:
  465. connection = connect()
  466. try:
  467. with connection.cursor() as cursor:
  468. cursor.execute(
  469. """
  470. UPDATE realtime_control_ad_state
  471. SET operator_pause_mode=NULL,
  472. operator_resume_at=NULL,
  473. operator_command_id=NULL,
  474. operator_paused_from_status=NULL,
  475. operator_paused_at=NULL,
  476. last_action=%s,
  477. last_action_at=%s,
  478. last_seen_at=%s
  479. WHERE account_id=%s AND adgroup_id=%s
  480. """,
  481. (action, action_at, action_at, account_id, adgroup_id),
  482. )
  483. finally:
  484. connection.close()
  485. def load_operator_pauses(
  486. account_ids: list[int] | None = None,
  487. ) -> list[dict[str, Any]]:
  488. params: list[Any] = []
  489. where = "WHERE operator_pause_mode IS NOT NULL"
  490. if account_ids is not None:
  491. if not account_ids:
  492. return []
  493. where += f" AND account_id IN ({', '.join(['%s'] * len(account_ids))})"
  494. params.extend(account_ids)
  495. connection = connect()
  496. try:
  497. with connection.cursor() as cursor:
  498. cursor.execute(
  499. f"""
  500. SELECT *
  501. FROM realtime_control_ad_state
  502. {where}
  503. ORDER BY account_id, adgroup_id
  504. """,
  505. params,
  506. )
  507. return list(cursor.fetchall())
  508. finally:
  509. connection.close()