monitoring_dispatch.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. """Request preflight and audit leases for the existing collector. Never dispatches or grants spend."""
  2. from contextlib import closing
  3. import csv
  4. from datetime import datetime, timedelta, timezone
  5. from decimal import Decimal, InvalidOperation
  6. import io
  7. import json
  8. from pathlib import Path
  9. import secrets
  10. import sqlite3
  11. from unified_store import monitoring_connection, monitoring_available
  12. import zipfile
  13. from monitoring_store import canonical, exact_id, initialize, need, read_state, sha
  14. SCHEMA = 'ksf.monitoring-request-guard.v1'
  15. # The settled user instruction is deliberately not an environment-variable switch.
  16. STOP = {'authorizedMinor': 5000, 'spendLimitMinor': 4620, 'chargedMinor': 4620,
  17. 'unsettledMinor': 0, 'protectedMinor': 380, 'paidDispatchStopped': True}
  18. DDL = '''
  19. CREATE TABLE IF NOT EXISTS dispatch_closeouts(
  20. digest TEXT PRIMARY KEY, imported_at TEXT NOT NULL, summary TEXT NOT NULL,
  21. csv_sha256 TEXT NOT NULL, identified_rows INTEGER NOT NULL);
  22. CREATE TABLE IF NOT EXISTS dispatch_history(
  23. closeout_sha256 TEXT NOT NULL, row_number INTEGER NOT NULL,
  24. platform TEXT NOT NULL, endpoint_id TEXT NOT NULL, product_id TEXT NOT NULL,
  25. page INTEGER NOT NULL, request_id TEXT NOT NULL, trace_id TEXT,
  26. charged_minor INTEGER NOT NULL, business_result TEXT NOT NULL,
  27. PRIMARY KEY(closeout_sha256,row_number), UNIQUE(platform,endpoint_id,request_id));
  28. CREATE TABLE IF NOT EXISTS dispatch_audits(
  29. id TEXT PRIMARY KEY, specification TEXT NOT NULL, generation TEXT NOT NULL,
  30. owner TEXT NOT NULL, token_hash TEXT NOT NULL, lease_until TEXT NOT NULL,
  31. state TEXT NOT NULL, updated_at TEXT NOT NULL);
  32. CREATE TABLE IF NOT EXISTS dispatch_events(
  33. id INTEGER PRIMARY KEY, audit_id TEXT, event TEXT NOT NULL, at TEXT NOT NULL,
  34. payload TEXT NOT NULL);
  35. '''
  36. PARAMS = {'jd.get_item_comments_v1': ('jd', 'reviews', {'itemId', 'page'}),
  37. 'jd.get_shop_item_list_v1': ('jd', 'listings', {'shopId', 'page'}),
  38. 'taobao.get_item_comment_v3': ('tmall', 'reviews', {'itemId', 'page', 'orderType'}),
  39. 'taobao.get_shop_item_list_v4': ('tmall', 'listings', {'sellerId', 'page'})}
  40. def now():
  41. return datetime.now(timezone.utc)
  42. def setup(root):
  43. initialize(root)
  44. with closing(monitoring_connection(root, timeout=20)) as c:
  45. c.executescript(DDL)
  46. c.execute('INSERT OR IGNORE INTO meta VALUES(?,?)', ('dispatchSchema', SCHEMA))
  47. need(c.execute('SELECT value FROM meta WHERE key=?', ('dispatchSchema',)).fetchone()[0] == SCHEMA,
  48. 'DISPATCH_SCHEMA_MISMATCH')
  49. c.commit()
  50. def connect(root, write=False):
  51. path = Path(root).resolve() / 'monitoring.sqlite'
  52. need(monitoring_available(root), 'MONITORING_STORE_NOT_INSTALLED')
  53. c = monitoring_connection(root, write=write, timeout=20)
  54. c.row_factory = sqlite3.Row
  55. if not write:
  56. c.execute('PRAGMA query_only=ON')
  57. c.execute('BEGIN IMMEDIATE' if write else 'BEGIN')
  58. return c
  59. def installed(c):
  60. ready = bool(c.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='dispatch_history'").fetchone())
  61. if ready:
  62. row = c.execute('SELECT value FROM meta WHERE key=?', ('dispatchSchema',)).fetchone()
  63. need(row and row[0] == SCHEMA, 'DISPATCH_SCHEMA_MISMATCH')
  64. return ready
  65. def event(c, ident, kind, payload):
  66. c.execute('INSERT INTO dispatch_events(audit_id,event,at,payload) VALUES(?,?,?,?)',
  67. (ident, kind, now().isoformat(), canonical(payload)))
  68. def minor(value):
  69. try:
  70. cents = Decimal(str(value)) * 100
  71. need(cents.is_finite() and cents >= 0 and cents == cents.to_integral_value(), 'EXACT_MONEY_REQUIRED')
  72. return int(cents)
  73. except (InvalidOperation, TypeError, ValueError):
  74. raise ValueError('EXACT_MONEY_REQUIRED') from None
  75. def import_closeout(root, archive, expected_sha256):
  76. """Import the already-settled 76-row handoff, retaining the aggregate 154-row budget basis."""
  77. need(isinstance(expected_sha256, str) and len(expected_sha256) == 64, 'CLOSEOUT_SHA_REQUIRED')
  78. raw = Path(archive).read_bytes()
  79. need(len(raw) <= 5_000_000 and sha(raw) == expected_sha256, 'CLOSEOUT_SHA_MISMATCH')
  80. with zipfile.ZipFile(io.BytesIO(raw)) as z:
  81. need(len(z.namelist()) == 3 and set(z.namelist()) == {'union.csv', 'unified-summary.json', 'FILES.sha256'}, 'INVALID_CLOSEOUT_FILES')
  82. need(all(p.file_size <= 2_000_000 for p in z.infolist()), 'CLOSEOUT_TOO_LARGE')
  83. verified = set()
  84. for line in z.read('FILES.sha256').decode('utf-8-sig').splitlines():
  85. digest, name = line.split(' ', 1)
  86. need(name in ('union.csv', 'unified-summary.json') and name not in verified and
  87. sha(z.read(name)) == digest, 'CLOSEOUT_MANIFEST_MISMATCH')
  88. verified.add(name)
  89. need(verified == {'union.csv', 'unified-summary.json'}, 'CLOSEOUT_MANIFEST_MISMATCH')
  90. csv_raw, summary_raw = z.read('union.csv'), z.read('unified-summary.json')
  91. summary = json.loads(summary_raw)
  92. need(summary.get('schema') == 'ksf.union-final.v1', 'INVALID_CLOSEOUT_SCHEMA')
  93. money = summary['钱']
  94. for field, expected in [('累计已扣Cny', 4620), ('其中本批队列Cny', 2280), ('其中此前轮次Cny', 2340),
  95. ('未决预留Cny', 0), ('授权Cny', 5000), ('支出上限Cny', 4620),
  96. ('剩余可派发上界Cny', 0), ('保底Cny', 380)]:
  97. need(minor(money[field]) == expected, 'CLOSEOUT_BUDGET_MISMATCH')
  98. ledger = summary['账本']
  99. need(ledger['行数'] == 154 and ledger['队列行'] == 76 and ledger['cache行'] == 9 and
  100. ledger['upstream行'] == 145 and ledger['队列cache'] == 0, 'CLOSEOUT_COUNTS_MISMATCH')
  101. rows = list(csv.DictReader(io.StringIO(csv_raw.decode('utf-8-sig'))))
  102. need(len(rows) == 76, 'CLOSEOUT_COUNTS_MISMATCH')
  103. entries, requests, slots = [], set(), set()
  104. for number, row in enumerate(rows, 2):
  105. product = exact_id(row['商品ID'])
  106. need(product.startswith('jd:') and product[3:].isdigit(), 'INVALID_CLOSEOUT_PRODUCT')
  107. page = row['页码']
  108. need(page.isdigit() and 1 <= int(page) <= 10000, 'INVALID_CLOSEOUT_PAGE')
  109. request = exact_id(row['requestId'])
  110. need(request not in requests and (product, int(page)) not in slots, 'DUPLICATE_CLOSEOUT_REQUEST')
  111. requests.add(request); slots.add((product, int(page)))
  112. charged = minor(row['实际扣费'])
  113. need(charged == 30, 'CLOSEOUT_ROW_COST_MISMATCH')
  114. entries.append((expected_sha256, number, 'jd', 'jd.get_item_comments_v1', product,
  115. int(page), request, None if row['trace'] in ('', '-') else row['trace'], charged, row['业务结果']))
  116. need(sum(row[8] for row in entries) == 2280, 'CLOSEOUT_ROW_COST_MISMATCH')
  117. setup(root)
  118. safe = {'settledAt': summary.get('at'), 'ledgerRows': 154, 'cacheRows': 9, 'upstreamRows': 145,
  119. 'identifiedQueueRows': 76, 'priorAggregateRows': 78, 'identifiedQueueChargedMinor': 2280,
  120. 'priorAggregateChargedMinor': 2340, 'all154RequestIdentitiesAvailable': False, **STOP}
  121. with closing(connect(root, True)) as c:
  122. existing = c.execute('SELECT * FROM dispatch_closeouts WHERE digest=?', (expected_sha256,)).fetchone()
  123. if existing:
  124. need(existing['summary'] == canonical(safe) and existing['csv_sha256'] == sha(csv_raw), 'CLOSEOUT_CHANGED')
  125. return {'ok': True, 'alreadyImported': True, 'identifiedRows': 76, 'dispatchEnabled': False}
  126. need(c.execute('SELECT count(*) FROM dispatch_closeouts').fetchone()[0] == 0, 'CLOSEOUT_ALREADY_FIXED')
  127. c.execute('INSERT INTO dispatch_closeouts VALUES(?,?,?,?,?)',
  128. (expected_sha256, now().isoformat(), canonical(safe), sha(csv_raw), 76))
  129. c.executemany('INSERT INTO dispatch_history VALUES(?,?,?,?,?,?,?,?,?,?)', entries)
  130. # Preserve the original archive bytes without leaking its old filesystem path to HTTP.
  131. target = Path(root) / 'assets' / (expected_sha256 + '.zip')
  132. if target.exists():
  133. need(sha(target.read_bytes()) == expected_sha256, 'STORED_ASSET_CHANGED')
  134. else:
  135. with target.open('xb') as stream:
  136. stream.write(raw)
  137. event(c, None, 'SETTLED_CLOSEOUT_IMPORTED', {'sha256': expected_sha256, 'identifiedRows': 76})
  138. c.commit()
  139. return {'ok': True, 'alreadyImported': False, 'identifiedRows': 76, 'dispatchEnabled': False, 'paidCalls': 0}
  140. def normalize(request):
  141. need(isinstance(request, dict) and set(request) == {'endpointId', 'params', 'window', 'generation'}, 'INVALID_PREFLIGHT_REQUEST')
  142. endpoint = request['endpointId']
  143. need(endpoint in PARAMS, 'INTERFACE_NOT_VERIFIED')
  144. platform, kind, required = PARAMS[endpoint]
  145. params = request['params']
  146. need(isinstance(params, dict) and set(params) == required, 'INVALID_COLLECTOR_PARAMS')
  147. converted = {}
  148. for key, value in params.items():
  149. if key == 'page':
  150. need(type(value) is int or isinstance(value, str) and value.isdigit(), 'EXACT_PAGE_REQUIRED')
  151. need(1 <= int(value) <= 10000, 'EXACT_PAGE_REQUIRED')
  152. converted[key] = int(value)
  153. elif key == 'orderType':
  154. need(value in ('general', 'feedbackdate'), 'INTERFACE_MODE_NOT_VERIFIED')
  155. converted[key] = value
  156. else:
  157. need(isinstance(value, str) and value.isdigit() and len(value) <= 50, 'EXACT_NUMERIC_ID_REQUIRED')
  158. converted[key] = value
  159. window, generation = exact_id(request['window']), exact_id(request['generation'])
  160. product = ('jd:' if platform == 'jd' else 'taobao:') + converted['itemId'] if kind == 'reviews' else None
  161. return {'endpointId': endpoint, 'params': converted, 'window': window, 'generation': generation,
  162. 'platform': platform, 'kind': kind, 'productId': product}
  163. def intent_key(spec):
  164. # Generation is a reference to research, not permission to repeat an upstream request.
  165. return sha(canonical([spec['endpointId'], spec['params'], spec['window']]).encode())
  166. def _decision(c, spec, runs, ignore_audit=None):
  167. reasons = ['PAID_COLLECTION_STOPPED']
  168. paid, responses, failed = [], [], []
  169. coverage, count = 'NOT_INSTALLED', 0
  170. if not installed(c):
  171. reasons.append('SETTLED_HISTORY_NOT_INSTALLED')
  172. else:
  173. count = c.execute('SELECT count(*) FROM dispatch_history').fetchone()[0]
  174. coverage = 'PARTIAL_IDENTITIES_WITH_SETTLED_AGGREGATE' if c.execute('SELECT 1 FROM dispatch_closeouts').fetchone() else 'SETTLED_AGGREGATE_NOT_INSTALLED'
  175. for row in c.execute('SELECT request_id,business_result FROM dispatch_history WHERE endpoint_id=? AND product_id=? AND page=?',
  176. (spec['endpointId'], spec['productId'], spec['params']['page'])):
  177. paid.append({'requestId': row['request_id'], 'businessResult': row['business_result']})
  178. from monitoring_ledger import matching, projection as ledger_projection
  179. ledger = ledger_projection(c)
  180. if ledger:
  181. count = ledger['providedLedgerRows']
  182. coverage = 'ALL_PROVIDED_LEDGER_IDENTITIES_WITH_PARTIAL_PARAMETER_BINDINGS'
  183. # The verified full ledger includes all 76 queue rows. Some queue request IDs
  184. # are placeholders and were reconciled via trace; only emit canonical ledger
  185. # identities, otherwise the same charge appears twice under two identifiers.
  186. paid = matching(c, spec)
  187. if paid:
  188. reasons.append('REQUEST_ALREADY_CHARGED_NO_AUTOMATIC_REPLAY')
  189. if not c.execute('SELECT 1 FROM dispatch_closeouts').fetchone():
  190. reasons.append('SETTLED_HISTORY_NOT_INSTALLED')
  191. candidates = list(runs)
  192. if c.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='pipeline_pages'").fetchone():
  193. for row in c.execute('SELECT p.descriptor,c.specification,c.id FROM pipeline_pages p JOIN pipeline_cycles c ON c.id=p.cycle_id'):
  194. source = json.loads(row['specification'])
  195. candidates.append({**source, 'runId': None, 'cycleId': row['id'], 'pages': [json.loads(row['descriptor'])]})
  196. seen_proofs = set()
  197. for run in candidates:
  198. if run['endpointId'] != spec['endpointId']:
  199. continue
  200. if spec['kind'] == 'reviews' and run['scope'].get('productId') != spec['productId']:
  201. continue
  202. if spec['kind'] == 'listings':
  203. # sellerId is a distinct namespace; never compare it to shopId.
  204. if spec['platform'] != 'jd' or run['scope'].get('shopId') != spec['params']['shopId']:
  205. continue
  206. for page in run['pages']:
  207. if page['page'] != spec['params']['page']:
  208. continue
  209. proof = (run['endpointId'], page['requestKey'])
  210. if proof in seen_proofs:
  211. continue
  212. seen_proofs.add(proof)
  213. found = {'runId': run['runId'], 'page': page['page'], 'requestKey': page['requestKey'],
  214. 'window': run['window'], 'status': page['status']}
  215. if run.get('cycleId'):
  216. found['cycleId'] = run['cycleId']
  217. (responses if page['status'] == 'success' else failed).append(found)
  218. if responses:
  219. reasons.append('EXISTING_RESPONSE_REQUIRES_REUSE_REVIEW')
  220. if failed:
  221. reasons.append('FAILED_OR_UNSETTLED_REQUEST_NO_AUTOMATIC_REPLAY')
  222. lease = None
  223. if installed(c):
  224. row = c.execute('SELECT id,generation,lease_until,state FROM dispatch_audits WHERE id=?', (intent_key(spec),)).fetchone()
  225. if row and row['state'] == 'CLAIMED' and datetime.fromisoformat(row['lease_until']) > now() and row['id'] != ignore_audit:
  226. reasons.append('REQUEST_AUDIT_ALREADY_CLAIMED')
  227. lease = {'until': row['lease_until'], 'sameGeneration': row['generation'] == spec['generation']}
  228. return {'dispatchAllowed': False, 'blockingReasons': reasons, 'alreadyCharged': paid,
  229. 'existingResponses': responses, 'failedOrUnsettled': failed, 'activeAudit': lease,
  230. 'costReservedMinor': 0, 'remainingDispatchMinor': 0,
  231. 'historicalIdentityCoverage': coverage, 'identifiedSettledRequestCount': count,
  232. 'note': '本接口仅核对与认领请求意图;没有发请求权限。历史身份未齐不补造;换窗口也不自动重发已收费页。'}
  233. def preflight(root, request, generation):
  234. spec = normalize(request)
  235. need(spec['generation'] == generation, 'LIBRARY_VERSION_CHANGED')
  236. runs = read_state(root)
  237. with closing(connect(root)) as c:
  238. decision = _decision(c, spec, runs)
  239. return {'ok': True, 'intentId': intent_key(spec), 'specification': spec, **decision,
  240. 'paidCalls': 0, 'researchDatabaseWrites': 0}
  241. def batch_preflight(root, requests, generation):
  242. need(isinstance(requests, list) and 1 <= len(requests) <= 500, 'INVALID_PREFLIGHT_BATCH')
  243. specs = [normalize(r) for r in requests]
  244. need(all(s['generation'] == generation for s in specs), 'LIBRARY_VERSION_CHANGED')
  245. runs, seen, rows = read_state(root), set(), []
  246. with closing(connect(root)) as c:
  247. for index, spec in enumerate(specs):
  248. key = intent_key(spec)
  249. decision = _decision(c, spec, runs)
  250. if key in seen:
  251. decision['blockingReasons'].append('DUPLICATE_REQUEST_IN_BATCH')
  252. seen.add(key)
  253. rows.append({'index': index, 'intentId': key, 'specification': spec, **decision})
  254. return {'ok': True, 'rows': rows, 'total': len(rows), 'distinctIntents': len(seen),
  255. 'dispatchAllowed': False, 'paidCalls': 0, 'costReservedMinor': 0}
  256. def claim(root, request, generation, owner, lease_seconds=1800):
  257. """Lease request verification only. No money reserved and no send transition exists."""
  258. spec = normalize(request)
  259. need(spec['generation'] == generation, 'LIBRARY_VERSION_CHANGED')
  260. exact_id(owner)
  261. need(type(lease_seconds) is int and 30 <= lease_seconds <= 3600, 'INVALID_AUDIT_LEASE')
  262. setup(root)
  263. ident, token = intent_key(spec), secrets.token_urlsafe(32)
  264. with closing(connect(root, True)) as c:
  265. prior = c.execute('SELECT * FROM dispatch_audits WHERE id=?', (ident,)).fetchone()
  266. need(not prior or prior['generation'] == generation, 'AUDIT_GENERATION_REVIEW_REQUIRED')
  267. need(not prior or prior['state'] != 'CLAIMED' or datetime.fromisoformat(prior['lease_until']) <= now(), 'REQUEST_AUDIT_ALREADY_CLAIMED')
  268. until = (now() + timedelta(seconds=lease_seconds)).isoformat()
  269. c.execute('INSERT OR REPLACE INTO dispatch_audits VALUES(?,?,?,?,?,?,?,?)',
  270. (ident, canonical(spec), generation, owner, sha(token.encode()), until, 'CLAIMED', now().isoformat()))
  271. event(c, ident, 'REQUEST_VERIFICATION_CLAIMED', {'generation': generation, 'dispatchAllowed': False, 'reservedMinor': 0})
  272. c.commit()
  273. return {'ok': True, 'intentId': ident, 'generation': generation, 'owner': owner, 'leaseToken': token,
  274. 'leaseUntil': until, 'dispatchAllowed': False, 'costReservedMinor': 0, 'purpose': 'REQUEST_VERIFICATION_ONLY'}
  275. def release(root, lease, generation):
  276. need(isinstance(lease, dict) and lease.get('generation') == generation, 'LIBRARY_VERSION_CHANGED')
  277. with closing(connect(root, True)) as c:
  278. row = c.execute('SELECT * FROM dispatch_audits WHERE id=?', (lease.get('intentId'),)).fetchone()
  279. need(row is not None and row['state'] == 'CLAIMED' and row['owner'] == lease.get('owner') and
  280. row['generation'] == generation and isinstance(lease.get('leaseToken'), str) and
  281. secrets.compare_digest(row['token_hash'], sha(lease['leaseToken'].encode())), 'AUDIT_LEASE_MISMATCH')
  282. need(datetime.fromisoformat(row['lease_until']) > now(), 'AUDIT_LEASE_EXPIRED')
  283. c.execute('UPDATE dispatch_audits SET state=?,updated_at=? WHERE id=?', ('RELEASED', now().isoformat(), row['id']))
  284. event(c, row['id'], 'REQUEST_VERIFICATION_RELEASED', {})
  285. c.commit()
  286. return {'ok': True, 'dispatchAllowed': False, 'costReservedMinor': 0}
  287. def projection(root, generation):
  288. """Redacted read model; no local paths, tokens, owner names or raw account metadata."""
  289. with closing(connect(root)) as c:
  290. ready = installed(c)
  291. summaries = [json.loads(r[0]) for r in c.execute('SELECT summary FROM dispatch_closeouts')] if ready else []
  292. leases = c.execute('SELECT generation,lease_until,state FROM dispatch_audits').fetchall() if ready else []
  293. count = c.execute('SELECT count(*) FROM dispatch_history').fetchone()[0] if ready else 0
  294. from monitoring_ledger import projection as ledger_projection
  295. ledger = ledger_projection(c)
  296. active = [r for r in leases if r['state'] == 'CLAIMED' and datetime.fromisoformat(r['lease_until']) > now()]
  297. return {'installed': ready, **STOP, 'dispatchAllowed': False, 'remainingDispatchMinor': 0,
  298. 'reservedMinor': 0, 'identifiedSettledRequests': ledger['providedLedgerRows'] if ledger else count,
  299. 'parameterBoundSettledRequests': ledger['requestSlotBoundRows'] if ledger else count,
  300. 'ledgerRows': summaries[0]['ledgerRows'] if summaries else None,
  301. 'aggregateOnlyRows': 0 if ledger else summaries[0]['priorAggregateRows'] if summaries else None,
  302. 'fullHistoricalIdentitiesVerified': bool(ledger),
  303. 'providedLedger': ledger,
  304. 'activeAuditLeases': sum(r['generation'] == generation for r in active),
  305. 'staleAuditLeases': sum(r['generation'] != generation for r in active),
  306. 'remoteCollectorsIntegrated': False,
  307. 'note': '统一请求核对与认领只用于资料复核;154行附件账本已逐条对齐,未绑定参数的行保持未知,不按请求名猜补;不重复加总。远端采集窗口尚未接入。' if ledger else '统一请求核对与认领只用于资料复核;本地76条逐件收费记录与154行总账分列,不重复加总。远端采集窗口尚未接入。'}