storage.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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. "initial_base_bid_fen": "INT DEFAULT NULL",
  53. "last_roi_scaled_at": "DATETIME DEFAULT NULL",
  54. "operator_pause_mode": "VARCHAR(32) DEFAULT NULL",
  55. "operator_resume_at": "DATETIME DEFAULT NULL",
  56. "operator_command_id": "VARCHAR(64) DEFAULT NULL",
  57. "operator_paused_from_status": "VARCHAR(50) DEFAULT NULL",
  58. "operator_paused_at": "DATETIME DEFAULT NULL",
  59. }
  60. for column, definition in migrations.items():
  61. if column not in existing_columns:
  62. cursor.execute(
  63. f"ALTER TABLE realtime_control_ad_state "
  64. f"ADD COLUMN {column} {definition}"
  65. )
  66. cursor.execute(
  67. """
  68. UPDATE realtime_control_ad_state
  69. SET initial_base_bid_fen=base_bid_fen
  70. WHERE initial_base_bid_fen IS NULL
  71. """
  72. )
  73. cursor.execute(
  74. """
  75. SELECT INDEX_NAME
  76. FROM information_schema.STATISTICS
  77. WHERE TABLE_SCHEMA=%s
  78. AND TABLE_NAME='realtime_control_ad_state'
  79. AND INDEX_NAME='idx_operator_pause'
  80. """,
  81. (os.environ["DB_NAME"],),
  82. )
  83. if not cursor.fetchone():
  84. cursor.execute(
  85. """
  86. CREATE INDEX idx_operator_pause
  87. ON realtime_control_ad_state
  88. (operator_pause_mode, operator_resume_at)
  89. """
  90. )
  91. finally:
  92. connection.close()
  93. @contextmanager
  94. def advisory_lock(lock_name: str) -> Iterator[bool]:
  95. connection = connect()
  96. acquired = False
  97. try:
  98. with connection.cursor() as cursor:
  99. cursor.execute("SELECT GET_LOCK(%s, 0) AS acquired", (lock_name,))
  100. acquired = bool((cursor.fetchone() or {}).get("acquired"))
  101. yield acquired
  102. finally:
  103. if acquired:
  104. try:
  105. with connection.cursor() as cursor:
  106. cursor.execute("SELECT RELEASE_LOCK(%s)", (lock_name,))
  107. except Exception:
  108. pass
  109. connection.close()
  110. def load_enabled_accounts() -> list[dict[str, Any]]:
  111. connection = connect()
  112. try:
  113. with connection.cursor() as cursor:
  114. cursor.execute(
  115. """
  116. SELECT c.account_id, c.audience_name, c.bid_scene
  117. FROM ad_creation_account_config c
  118. JOIN account_whitelist w ON w.account_id = c.account_id
  119. WHERE c.enabled = TRUE
  120. AND w.enabled = TRUE
  121. ORDER BY c.account_id
  122. """
  123. )
  124. return list(cursor.fetchall())
  125. finally:
  126. connection.close()
  127. def load_realtime_accounts() -> list[dict[str, Any]]:
  128. """All historical automation accounts still enabled by the whitelist."""
  129. connection = connect()
  130. try:
  131. with connection.cursor() as cursor:
  132. cursor.execute(
  133. """
  134. SELECT c.account_id, c.audience_name, c.bid_scene
  135. FROM ad_creation_account_config c
  136. JOIN account_whitelist w ON w.account_id = c.account_id
  137. WHERE w.enabled = TRUE
  138. ORDER BY c.account_id
  139. """
  140. )
  141. return list(cursor.fetchall())
  142. finally:
  143. connection.close()
  144. def load_managed_accounts() -> list[dict[str, Any]]:
  145. """Historical automation accounts still allowed by the account whitelist."""
  146. connection = connect()
  147. try:
  148. with connection.cursor() as cursor:
  149. cursor.execute(
  150. """
  151. SELECT c.account_id, c.audience_name, c.bid_scene, c.enabled
  152. FROM ad_creation_account_config c
  153. JOIN account_whitelist w ON w.account_id = c.account_id
  154. WHERE w.enabled = TRUE
  155. ORDER BY c.account_id
  156. """
  157. )
  158. return list(cursor.fetchall())
  159. finally:
  160. connection.close()
  161. def load_daily_state(control_date: date) -> dict[str, Any]:
  162. connection = connect()
  163. try:
  164. with connection.cursor() as cursor:
  165. cursor.execute(
  166. "SELECT * FROM realtime_control_daily_state WHERE control_date=%s",
  167. (control_date,),
  168. )
  169. return cursor.fetchone() or {}
  170. finally:
  171. connection.close()
  172. def save_daily_state(control_date: date, **values: Any) -> None:
  173. allowed = {
  174. "morning_recovery_done",
  175. "cutoff_done",
  176. "last_observed_partition",
  177. "last_observed_cpm",
  178. "last_decision",
  179. "last_inventory_refresh_at",
  180. "last_evaluated_at",
  181. }
  182. unknown = set(values) - allowed
  183. if unknown:
  184. raise ValueError(f"Unsupported daily-state fields: {sorted(unknown)}")
  185. columns = ["control_date", *values]
  186. params = [control_date, *values.values()]
  187. updates = ", ".join(f"{column}=VALUES({column})" for column in values)
  188. placeholders = ", ".join(["%s"] * len(columns))
  189. sql = (
  190. f"INSERT INTO realtime_control_daily_state ({', '.join(columns)}) "
  191. f"VALUES ({placeholders}) ON DUPLICATE KEY UPDATE {updates}"
  192. )
  193. connection = connect()
  194. try:
  195. with connection.cursor() as cursor:
  196. cursor.execute(sql, params)
  197. finally:
  198. connection.close()
  199. def load_ad_states(account_id: int) -> dict[int, dict[str, Any]]:
  200. connection = connect()
  201. try:
  202. with connection.cursor() as cursor:
  203. cursor.execute(
  204. "SELECT * FROM realtime_control_ad_state WHERE account_id=%s",
  205. (account_id,),
  206. )
  207. return {int(row["adgroup_id"]): row for row in cursor.fetchall()}
  208. finally:
  209. connection.close()
  210. def upsert_ad_state(
  211. *,
  212. account_id: int,
  213. adgroup_id: int,
  214. adgroup_name: str,
  215. bid_field: str,
  216. base_bid_fen: int,
  217. boosted_date: date | None,
  218. paused_by_strategy: bool,
  219. pause_reason: str | None,
  220. last_action: str,
  221. action_at: datetime,
  222. ) -> None:
  223. connection = connect()
  224. try:
  225. with connection.cursor() as cursor:
  226. cursor.execute(
  227. """
  228. INSERT INTO realtime_control_ad_state
  229. (account_id, adgroup_id, adgroup_name, bid_field, base_bid_fen,
  230. initial_base_bid_fen,
  231. boosted_date, paused_by_strategy, pause_reason, last_action,
  232. last_action_at, last_seen_at)
  233. VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
  234. ON DUPLICATE KEY UPDATE
  235. adgroup_name=VALUES(adgroup_name),
  236. bid_field=VALUES(bid_field),
  237. initial_base_bid_fen=COALESCE(
  238. initial_base_bid_fen,
  239. VALUES(initial_base_bid_fen)
  240. ),
  241. boosted_date=VALUES(boosted_date),
  242. paused_by_strategy=VALUES(paused_by_strategy),
  243. pause_reason=VALUES(pause_reason),
  244. last_action=VALUES(last_action),
  245. last_action_at=VALUES(last_action_at),
  246. last_seen_at=VALUES(last_seen_at)
  247. """,
  248. (
  249. account_id,
  250. adgroup_id,
  251. adgroup_name,
  252. bid_field,
  253. base_bid_fen,
  254. base_bid_fen,
  255. boosted_date,
  256. paused_by_strategy,
  257. pause_reason,
  258. last_action,
  259. action_at,
  260. action_at,
  261. ),
  262. )
  263. finally:
  264. connection.close()
  265. def sync_roi_base_bid(
  266. *,
  267. account_id: int,
  268. adgroup_id: int,
  269. adgroup_name: str,
  270. bid_field: str,
  271. initial_base_bid_fen: int,
  272. new_base_bid_fen: int,
  273. boosted_date: date | None,
  274. action_at: datetime,
  275. ) -> None:
  276. """Persist a permanent ROI base bid without losing intraday boost state."""
  277. connection = connect()
  278. try:
  279. with connection.cursor() as cursor:
  280. cursor.execute(
  281. """
  282. INSERT INTO realtime_control_ad_state
  283. (account_id, adgroup_id, adgroup_name, bid_field,
  284. base_bid_fen, initial_base_bid_fen, boosted_date,
  285. paused_by_strategy, pause_reason, last_action,
  286. last_action_at, last_seen_at, last_roi_scaled_at)
  287. VALUES (%s,%s,%s,%s,%s,%s,%s,FALSE,NULL,'ROI_SCALE',%s,%s,%s)
  288. ON DUPLICATE KEY UPDATE
  289. adgroup_name=VALUES(adgroup_name),
  290. bid_field=VALUES(bid_field),
  291. base_bid_fen=VALUES(base_bid_fen),
  292. initial_base_bid_fen=COALESCE(
  293. initial_base_bid_fen,
  294. VALUES(initial_base_bid_fen)
  295. ),
  296. boosted_date=VALUES(boosted_date),
  297. last_action='ROI_SCALE',
  298. last_action_at=VALUES(last_action_at),
  299. last_seen_at=VALUES(last_seen_at),
  300. last_roi_scaled_at=VALUES(last_roi_scaled_at)
  301. """,
  302. (
  303. account_id,
  304. adgroup_id,
  305. adgroup_name,
  306. bid_field,
  307. new_base_bid_fen,
  308. initial_base_bid_fen,
  309. boosted_date,
  310. action_at,
  311. action_at,
  312. action_at,
  313. ),
  314. )
  315. finally:
  316. connection.close()
  317. def insert_action_log(record: dict[str, Any]) -> None:
  318. columns = [
  319. "run_id",
  320. "control_date",
  321. "observed_partition",
  322. "observed_cpm",
  323. "decision",
  324. "account_id",
  325. "adgroup_id",
  326. "adgroup_name",
  327. "bid_field",
  328. "base_bid_fen",
  329. "before_bid_fen",
  330. "target_bid_fen",
  331. "before_status",
  332. "target_status",
  333. "apply_mode",
  334. "execution_status",
  335. "error_message",
  336. ]
  337. connection = connect()
  338. try:
  339. with connection.cursor() as cursor:
  340. cursor.execute(
  341. f"INSERT INTO realtime_control_action_log ({', '.join(columns)}) "
  342. f"VALUES ({', '.join(['%s'] * len(columns))})",
  343. [record.get(column) for column in columns],
  344. )
  345. finally:
  346. connection.close()
  347. def create_operator_command(record: dict[str, Any]) -> dict[str, Any]:
  348. connection = connect()
  349. try:
  350. with connection.cursor() as cursor:
  351. try:
  352. cursor.execute(
  353. """
  354. INSERT INTO operator_command
  355. (command_id, source_message_id, chat_id, sender_open_id,
  356. sender_name, action, scope_type, target_account_ids,
  357. status, preview_account_count, preview_ad_count, expires_at)
  358. VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
  359. """,
  360. (
  361. record["command_id"],
  362. record["source_message_id"],
  363. record["chat_id"],
  364. record["sender_open_id"],
  365. record.get("sender_name"),
  366. record["action"],
  367. record["scope_type"],
  368. json.dumps(record["target_account_ids"]),
  369. record["status"],
  370. record.get("preview_account_count", 0),
  371. record.get("preview_ad_count", 0),
  372. record.get("expires_at"),
  373. ),
  374. )
  375. except pymysql.err.IntegrityError:
  376. cursor.execute(
  377. "SELECT * FROM operator_command WHERE source_message_id=%s",
  378. (record["source_message_id"],),
  379. )
  380. existing = cursor.fetchone()
  381. if existing:
  382. existing["target_account_ids"] = json.loads(
  383. existing.get("target_account_ids") or "[]"
  384. )
  385. return existing
  386. raise
  387. return load_operator_command(record["command_id"]) or {}
  388. finally:
  389. connection.close()
  390. def load_operator_command(command_id: str) -> dict[str, Any] | None:
  391. connection = connect()
  392. try:
  393. with connection.cursor() as cursor:
  394. cursor.execute(
  395. "SELECT * FROM operator_command WHERE command_id=%s",
  396. (command_id,),
  397. )
  398. row = cursor.fetchone()
  399. if row:
  400. row["target_account_ids"] = json.loads(
  401. row.get("target_account_ids") or "[]"
  402. )
  403. return row
  404. finally:
  405. connection.close()
  406. def update_operator_command(command_id: str, status: str, **values: Any) -> None:
  407. allowed = {"confirmed_at", "executed_at", "error_message"}
  408. unknown = set(values) - allowed
  409. if unknown:
  410. raise ValueError(f"Unsupported operator-command fields: {sorted(unknown)}")
  411. assignments = ["status=%s"]
  412. params: list[Any] = [status]
  413. for column, value in values.items():
  414. assignments.append(f"{column}=%s")
  415. params.append(value)
  416. params.append(command_id)
  417. connection = connect()
  418. try:
  419. with connection.cursor() as cursor:
  420. cursor.execute(
  421. f"UPDATE operator_command SET {', '.join(assignments)} "
  422. "WHERE command_id=%s",
  423. params,
  424. )
  425. finally:
  426. connection.close()
  427. def transition_operator_command(
  428. command_id: str,
  429. *,
  430. expected_statuses: set[str],
  431. target_status: str,
  432. **values: Any,
  433. ) -> bool:
  434. allowed = {"confirmed_at", "executed_at", "error_message"}
  435. unknown = set(values) - allowed
  436. if unknown:
  437. raise ValueError(f"Unsupported operator-command fields: {sorted(unknown)}")
  438. if not expected_statuses:
  439. raise ValueError("expected_statuses must not be empty")
  440. assignments = ["status=%s"]
  441. params: list[Any] = [target_status]
  442. for column, value in values.items():
  443. assignments.append(f"{column}=%s")
  444. params.append(value)
  445. placeholders = ", ".join(["%s"] * len(expected_statuses))
  446. params.extend([command_id, *sorted(expected_statuses)])
  447. connection = connect()
  448. try:
  449. with connection.cursor() as cursor:
  450. affected = cursor.execute(
  451. f"""
  452. UPDATE operator_command
  453. SET {', '.join(assignments)}
  454. WHERE command_id=%s
  455. AND status IN ({placeholders})
  456. """,
  457. params,
  458. )
  459. return affected == 1
  460. finally:
  461. connection.close()
  462. def insert_operator_command_item(record: dict[str, Any]) -> None:
  463. columns = [
  464. "command_id",
  465. "account_id",
  466. "audience_name",
  467. "adgroup_id",
  468. "adgroup_name",
  469. "before_status",
  470. "target_status",
  471. "readback_status",
  472. "execution_status",
  473. "error_message",
  474. ]
  475. connection = connect()
  476. try:
  477. with connection.cursor() as cursor:
  478. cursor.execute(
  479. f"INSERT INTO operator_command_item ({', '.join(columns)}) "
  480. f"VALUES ({', '.join(['%s'] * len(columns))})",
  481. [record.get(column) for column in columns],
  482. )
  483. finally:
  484. connection.close()
  485. def set_operator_pause(
  486. *,
  487. account_id: int,
  488. adgroup_id: int,
  489. mode: str,
  490. resume_at: datetime | None,
  491. command_id: str,
  492. paused_from_status: str,
  493. paused_at: datetime,
  494. ) -> None:
  495. connection = connect()
  496. try:
  497. with connection.cursor() as cursor:
  498. cursor.execute(
  499. """
  500. UPDATE realtime_control_ad_state
  501. SET operator_pause_mode=%s,
  502. operator_resume_at=%s,
  503. operator_command_id=%s,
  504. operator_paused_from_status=%s,
  505. operator_paused_at=%s,
  506. last_action='OPERATOR_PAUSE',
  507. last_action_at=%s,
  508. last_seen_at=%s
  509. WHERE account_id=%s AND adgroup_id=%s
  510. """,
  511. (
  512. mode,
  513. resume_at,
  514. command_id,
  515. paused_from_status,
  516. paused_at,
  517. paused_at,
  518. paused_at,
  519. account_id,
  520. adgroup_id,
  521. ),
  522. )
  523. finally:
  524. connection.close()
  525. def clear_operator_pause(
  526. account_id: int,
  527. adgroup_id: int,
  528. *,
  529. action: str,
  530. action_at: datetime,
  531. ) -> None:
  532. connection = connect()
  533. try:
  534. with connection.cursor() as cursor:
  535. cursor.execute(
  536. """
  537. UPDATE realtime_control_ad_state
  538. SET operator_pause_mode=NULL,
  539. operator_resume_at=NULL,
  540. operator_command_id=NULL,
  541. operator_paused_from_status=NULL,
  542. operator_paused_at=NULL,
  543. last_action=%s,
  544. last_action_at=%s,
  545. last_seen_at=%s
  546. WHERE account_id=%s AND adgroup_id=%s
  547. """,
  548. (action, action_at, action_at, account_id, adgroup_id),
  549. )
  550. finally:
  551. connection.close()
  552. def load_operator_pauses(
  553. account_ids: list[int] | None = None,
  554. ) -> list[dict[str, Any]]:
  555. params: list[Any] = []
  556. where = "WHERE operator_pause_mode IS NOT NULL"
  557. if account_ids is not None:
  558. if not account_ids:
  559. return []
  560. where += f" AND account_id IN ({', '.join(['%s'] * len(account_ids))})"
  561. params.extend(account_ids)
  562. connection = connect()
  563. try:
  564. with connection.cursor() as cursor:
  565. cursor.execute(
  566. f"""
  567. SELECT *
  568. FROM realtime_control_ad_state
  569. {where}
  570. ORDER BY account_id, adgroup_id
  571. """,
  572. params,
  573. )
  574. return list(cursor.fetchall())
  575. finally:
  576. connection.close()