| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339 |
- """Request preflight and audit leases for the existing collector. Never dispatches or grants spend."""
- from contextlib import closing
- import csv
- from datetime import datetime, timedelta, timezone
- from decimal import Decimal, InvalidOperation
- import io
- import json
- from pathlib import Path
- import secrets
- import sqlite3
- from unified_store import monitoring_connection, monitoring_available
- import zipfile
- from monitoring_store import canonical, exact_id, initialize, need, read_state, sha
- SCHEMA = 'ksf.monitoring-request-guard.v1'
- # The settled user instruction is deliberately not an environment-variable switch.
- STOP = {'authorizedMinor': 5000, 'spendLimitMinor': 4620, 'chargedMinor': 4620,
- 'unsettledMinor': 0, 'protectedMinor': 380, 'paidDispatchStopped': True}
- DDL = '''
- CREATE TABLE IF NOT EXISTS dispatch_closeouts(
- digest TEXT PRIMARY KEY, imported_at TEXT NOT NULL, summary TEXT NOT NULL,
- csv_sha256 TEXT NOT NULL, identified_rows INTEGER NOT NULL);
- CREATE TABLE IF NOT EXISTS dispatch_history(
- closeout_sha256 TEXT NOT NULL, row_number INTEGER NOT NULL,
- platform TEXT NOT NULL, endpoint_id TEXT NOT NULL, product_id TEXT NOT NULL,
- page INTEGER NOT NULL, request_id TEXT NOT NULL, trace_id TEXT,
- charged_minor INTEGER NOT NULL, business_result TEXT NOT NULL,
- PRIMARY KEY(closeout_sha256,row_number), UNIQUE(platform,endpoint_id,request_id));
- CREATE TABLE IF NOT EXISTS dispatch_audits(
- id TEXT PRIMARY KEY, specification TEXT NOT NULL, generation TEXT NOT NULL,
- owner TEXT NOT NULL, token_hash TEXT NOT NULL, lease_until TEXT NOT NULL,
- state TEXT NOT NULL, updated_at TEXT NOT NULL);
- CREATE TABLE IF NOT EXISTS dispatch_events(
- id INTEGER PRIMARY KEY, audit_id TEXT, event TEXT NOT NULL, at TEXT NOT NULL,
- payload TEXT NOT NULL);
- '''
- PARAMS = {'jd.get_item_comments_v1': ('jd', 'reviews', {'itemId', 'page'}),
- 'jd.get_shop_item_list_v1': ('jd', 'listings', {'shopId', 'page'}),
- 'taobao.get_item_comment_v3': ('tmall', 'reviews', {'itemId', 'page', 'orderType'}),
- 'taobao.get_shop_item_list_v4': ('tmall', 'listings', {'sellerId', 'page'})}
- def now():
- return datetime.now(timezone.utc)
- def setup(root):
- initialize(root)
- with closing(monitoring_connection(root, timeout=20)) as c:
- c.executescript(DDL)
- c.execute('INSERT OR IGNORE INTO meta VALUES(?,?)', ('dispatchSchema', SCHEMA))
- need(c.execute('SELECT value FROM meta WHERE key=?', ('dispatchSchema',)).fetchone()[0] == SCHEMA,
- 'DISPATCH_SCHEMA_MISMATCH')
- c.commit()
- def connect(root, write=False):
- path = Path(root).resolve() / 'monitoring.sqlite'
- need(monitoring_available(root), 'MONITORING_STORE_NOT_INSTALLED')
- c = monitoring_connection(root, write=write, timeout=20)
- c.row_factory = sqlite3.Row
- if not write:
- c.execute('PRAGMA query_only=ON')
- c.execute('BEGIN IMMEDIATE' if write else 'BEGIN')
- return c
- def installed(c):
- ready = bool(c.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='dispatch_history'").fetchone())
- if ready:
- row = c.execute('SELECT value FROM meta WHERE key=?', ('dispatchSchema',)).fetchone()
- need(row and row[0] == SCHEMA, 'DISPATCH_SCHEMA_MISMATCH')
- return ready
- def event(c, ident, kind, payload):
- c.execute('INSERT INTO dispatch_events(audit_id,event,at,payload) VALUES(?,?,?,?)',
- (ident, kind, now().isoformat(), canonical(payload)))
- def minor(value):
- try:
- cents = Decimal(str(value)) * 100
- need(cents.is_finite() and cents >= 0 and cents == cents.to_integral_value(), 'EXACT_MONEY_REQUIRED')
- return int(cents)
- except (InvalidOperation, TypeError, ValueError):
- raise ValueError('EXACT_MONEY_REQUIRED') from None
- def import_closeout(root, archive, expected_sha256):
- """Import the already-settled 76-row handoff, retaining the aggregate 154-row budget basis."""
- need(isinstance(expected_sha256, str) and len(expected_sha256) == 64, 'CLOSEOUT_SHA_REQUIRED')
- raw = Path(archive).read_bytes()
- need(len(raw) <= 5_000_000 and sha(raw) == expected_sha256, 'CLOSEOUT_SHA_MISMATCH')
- with zipfile.ZipFile(io.BytesIO(raw)) as z:
- need(len(z.namelist()) == 3 and set(z.namelist()) == {'union.csv', 'unified-summary.json', 'FILES.sha256'}, 'INVALID_CLOSEOUT_FILES')
- need(all(p.file_size <= 2_000_000 for p in z.infolist()), 'CLOSEOUT_TOO_LARGE')
- verified = set()
- for line in z.read('FILES.sha256').decode('utf-8-sig').splitlines():
- digest, name = line.split(' ', 1)
- need(name in ('union.csv', 'unified-summary.json') and name not in verified and
- sha(z.read(name)) == digest, 'CLOSEOUT_MANIFEST_MISMATCH')
- verified.add(name)
- need(verified == {'union.csv', 'unified-summary.json'}, 'CLOSEOUT_MANIFEST_MISMATCH')
- csv_raw, summary_raw = z.read('union.csv'), z.read('unified-summary.json')
- summary = json.loads(summary_raw)
- need(summary.get('schema') == 'ksf.union-final.v1', 'INVALID_CLOSEOUT_SCHEMA')
- money = summary['钱']
- for field, expected in [('累计已扣Cny', 4620), ('其中本批队列Cny', 2280), ('其中此前轮次Cny', 2340),
- ('未决预留Cny', 0), ('授权Cny', 5000), ('支出上限Cny', 4620),
- ('剩余可派发上界Cny', 0), ('保底Cny', 380)]:
- need(minor(money[field]) == expected, 'CLOSEOUT_BUDGET_MISMATCH')
- ledger = summary['账本']
- need(ledger['行数'] == 154 and ledger['队列行'] == 76 and ledger['cache行'] == 9 and
- ledger['upstream行'] == 145 and ledger['队列cache'] == 0, 'CLOSEOUT_COUNTS_MISMATCH')
- rows = list(csv.DictReader(io.StringIO(csv_raw.decode('utf-8-sig'))))
- need(len(rows) == 76, 'CLOSEOUT_COUNTS_MISMATCH')
- entries, requests, slots = [], set(), set()
- for number, row in enumerate(rows, 2):
- product = exact_id(row['商品ID'])
- need(product.startswith('jd:') and product[3:].isdigit(), 'INVALID_CLOSEOUT_PRODUCT')
- page = row['页码']
- need(page.isdigit() and 1 <= int(page) <= 10000, 'INVALID_CLOSEOUT_PAGE')
- request = exact_id(row['requestId'])
- need(request not in requests and (product, int(page)) not in slots, 'DUPLICATE_CLOSEOUT_REQUEST')
- requests.add(request); slots.add((product, int(page)))
- charged = minor(row['实际扣费'])
- need(charged == 30, 'CLOSEOUT_ROW_COST_MISMATCH')
- entries.append((expected_sha256, number, 'jd', 'jd.get_item_comments_v1', product,
- int(page), request, None if row['trace'] in ('', '-') else row['trace'], charged, row['业务结果']))
- need(sum(row[8] for row in entries) == 2280, 'CLOSEOUT_ROW_COST_MISMATCH')
- setup(root)
- safe = {'settledAt': summary.get('at'), 'ledgerRows': 154, 'cacheRows': 9, 'upstreamRows': 145,
- 'identifiedQueueRows': 76, 'priorAggregateRows': 78, 'identifiedQueueChargedMinor': 2280,
- 'priorAggregateChargedMinor': 2340, 'all154RequestIdentitiesAvailable': False, **STOP}
- with closing(connect(root, True)) as c:
- existing = c.execute('SELECT * FROM dispatch_closeouts WHERE digest=?', (expected_sha256,)).fetchone()
- if existing:
- need(existing['summary'] == canonical(safe) and existing['csv_sha256'] == sha(csv_raw), 'CLOSEOUT_CHANGED')
- return {'ok': True, 'alreadyImported': True, 'identifiedRows': 76, 'dispatchEnabled': False}
- need(c.execute('SELECT count(*) FROM dispatch_closeouts').fetchone()[0] == 0, 'CLOSEOUT_ALREADY_FIXED')
- c.execute('INSERT INTO dispatch_closeouts VALUES(?,?,?,?,?)',
- (expected_sha256, now().isoformat(), canonical(safe), sha(csv_raw), 76))
- c.executemany('INSERT INTO dispatch_history VALUES(?,?,?,?,?,?,?,?,?,?)', entries)
- # Preserve the original archive bytes without leaking its old filesystem path to HTTP.
- target = Path(root) / 'assets' / (expected_sha256 + '.zip')
- if target.exists():
- need(sha(target.read_bytes()) == expected_sha256, 'STORED_ASSET_CHANGED')
- else:
- with target.open('xb') as stream:
- stream.write(raw)
- event(c, None, 'SETTLED_CLOSEOUT_IMPORTED', {'sha256': expected_sha256, 'identifiedRows': 76})
- c.commit()
- return {'ok': True, 'alreadyImported': False, 'identifiedRows': 76, 'dispatchEnabled': False, 'paidCalls': 0}
- def normalize(request):
- need(isinstance(request, dict) and set(request) == {'endpointId', 'params', 'window', 'generation'}, 'INVALID_PREFLIGHT_REQUEST')
- endpoint = request['endpointId']
- need(endpoint in PARAMS, 'INTERFACE_NOT_VERIFIED')
- platform, kind, required = PARAMS[endpoint]
- params = request['params']
- need(isinstance(params, dict) and set(params) == required, 'INVALID_COLLECTOR_PARAMS')
- converted = {}
- for key, value in params.items():
- if key == 'page':
- need(type(value) is int or isinstance(value, str) and value.isdigit(), 'EXACT_PAGE_REQUIRED')
- need(1 <= int(value) <= 10000, 'EXACT_PAGE_REQUIRED')
- converted[key] = int(value)
- elif key == 'orderType':
- need(value in ('general', 'feedbackdate'), 'INTERFACE_MODE_NOT_VERIFIED')
- converted[key] = value
- else:
- need(isinstance(value, str) and value.isdigit() and len(value) <= 50, 'EXACT_NUMERIC_ID_REQUIRED')
- converted[key] = value
- window, generation = exact_id(request['window']), exact_id(request['generation'])
- product = ('jd:' if platform == 'jd' else 'taobao:') + converted['itemId'] if kind == 'reviews' else None
- return {'endpointId': endpoint, 'params': converted, 'window': window, 'generation': generation,
- 'platform': platform, 'kind': kind, 'productId': product}
- def intent_key(spec):
- # Generation is a reference to research, not permission to repeat an upstream request.
- return sha(canonical([spec['endpointId'], spec['params'], spec['window']]).encode())
- def _decision(c, spec, runs, ignore_audit=None):
- reasons = ['PAID_COLLECTION_STOPPED']
- paid, responses, failed = [], [], []
- coverage, count = 'NOT_INSTALLED', 0
- if not installed(c):
- reasons.append('SETTLED_HISTORY_NOT_INSTALLED')
- else:
- count = c.execute('SELECT count(*) FROM dispatch_history').fetchone()[0]
- coverage = 'PARTIAL_IDENTITIES_WITH_SETTLED_AGGREGATE' if c.execute('SELECT 1 FROM dispatch_closeouts').fetchone() else 'SETTLED_AGGREGATE_NOT_INSTALLED'
- for row in c.execute('SELECT request_id,business_result FROM dispatch_history WHERE endpoint_id=? AND product_id=? AND page=?',
- (spec['endpointId'], spec['productId'], spec['params']['page'])):
- paid.append({'requestId': row['request_id'], 'businessResult': row['business_result']})
- from monitoring_ledger import matching, projection as ledger_projection
- ledger = ledger_projection(c)
- if ledger:
- count = ledger['providedLedgerRows']
- coverage = 'ALL_PROVIDED_LEDGER_IDENTITIES_WITH_PARTIAL_PARAMETER_BINDINGS'
- # The verified full ledger includes all 76 queue rows. Some queue request IDs
- # are placeholders and were reconciled via trace; only emit canonical ledger
- # identities, otherwise the same charge appears twice under two identifiers.
- paid = matching(c, spec)
- if paid:
- reasons.append('REQUEST_ALREADY_CHARGED_NO_AUTOMATIC_REPLAY')
- if not c.execute('SELECT 1 FROM dispatch_closeouts').fetchone():
- reasons.append('SETTLED_HISTORY_NOT_INSTALLED')
- candidates = list(runs)
- if c.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='pipeline_pages'").fetchone():
- 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'):
- source = json.loads(row['specification'])
- candidates.append({**source, 'runId': None, 'cycleId': row['id'], 'pages': [json.loads(row['descriptor'])]})
- seen_proofs = set()
- for run in candidates:
- if run['endpointId'] != spec['endpointId']:
- continue
- if spec['kind'] == 'reviews' and run['scope'].get('productId') != spec['productId']:
- continue
- if spec['kind'] == 'listings':
- # sellerId is a distinct namespace; never compare it to shopId.
- if spec['platform'] != 'jd' or run['scope'].get('shopId') != spec['params']['shopId']:
- continue
- for page in run['pages']:
- if page['page'] != spec['params']['page']:
- continue
- proof = (run['endpointId'], page['requestKey'])
- if proof in seen_proofs:
- continue
- seen_proofs.add(proof)
- found = {'runId': run['runId'], 'page': page['page'], 'requestKey': page['requestKey'],
- 'window': run['window'], 'status': page['status']}
- if run.get('cycleId'):
- found['cycleId'] = run['cycleId']
- (responses if page['status'] == 'success' else failed).append(found)
- if responses:
- reasons.append('EXISTING_RESPONSE_REQUIRES_REUSE_REVIEW')
- if failed:
- reasons.append('FAILED_OR_UNSETTLED_REQUEST_NO_AUTOMATIC_REPLAY')
- lease = None
- if installed(c):
- row = c.execute('SELECT id,generation,lease_until,state FROM dispatch_audits WHERE id=?', (intent_key(spec),)).fetchone()
- if row and row['state'] == 'CLAIMED' and datetime.fromisoformat(row['lease_until']) > now() and row['id'] != ignore_audit:
- reasons.append('REQUEST_AUDIT_ALREADY_CLAIMED')
- lease = {'until': row['lease_until'], 'sameGeneration': row['generation'] == spec['generation']}
- return {'dispatchAllowed': False, 'blockingReasons': reasons, 'alreadyCharged': paid,
- 'existingResponses': responses, 'failedOrUnsettled': failed, 'activeAudit': lease,
- 'costReservedMinor': 0, 'remainingDispatchMinor': 0,
- 'historicalIdentityCoverage': coverage, 'identifiedSettledRequestCount': count,
- 'note': '本接口仅核对与认领请求意图;没有发请求权限。历史身份未齐不补造;换窗口也不自动重发已收费页。'}
- def preflight(root, request, generation):
- spec = normalize(request)
- need(spec['generation'] == generation, 'LIBRARY_VERSION_CHANGED')
- runs = read_state(root)
- with closing(connect(root)) as c:
- decision = _decision(c, spec, runs)
- return {'ok': True, 'intentId': intent_key(spec), 'specification': spec, **decision,
- 'paidCalls': 0, 'researchDatabaseWrites': 0}
- def batch_preflight(root, requests, generation):
- need(isinstance(requests, list) and 1 <= len(requests) <= 500, 'INVALID_PREFLIGHT_BATCH')
- specs = [normalize(r) for r in requests]
- need(all(s['generation'] == generation for s in specs), 'LIBRARY_VERSION_CHANGED')
- runs, seen, rows = read_state(root), set(), []
- with closing(connect(root)) as c:
- for index, spec in enumerate(specs):
- key = intent_key(spec)
- decision = _decision(c, spec, runs)
- if key in seen:
- decision['blockingReasons'].append('DUPLICATE_REQUEST_IN_BATCH')
- seen.add(key)
- rows.append({'index': index, 'intentId': key, 'specification': spec, **decision})
- return {'ok': True, 'rows': rows, 'total': len(rows), 'distinctIntents': len(seen),
- 'dispatchAllowed': False, 'paidCalls': 0, 'costReservedMinor': 0}
- def claim(root, request, generation, owner, lease_seconds=1800):
- """Lease request verification only. No money reserved and no send transition exists."""
- spec = normalize(request)
- need(spec['generation'] == generation, 'LIBRARY_VERSION_CHANGED')
- exact_id(owner)
- need(type(lease_seconds) is int and 30 <= lease_seconds <= 3600, 'INVALID_AUDIT_LEASE')
- setup(root)
- ident, token = intent_key(spec), secrets.token_urlsafe(32)
- with closing(connect(root, True)) as c:
- prior = c.execute('SELECT * FROM dispatch_audits WHERE id=?', (ident,)).fetchone()
- need(not prior or prior['generation'] == generation, 'AUDIT_GENERATION_REVIEW_REQUIRED')
- need(not prior or prior['state'] != 'CLAIMED' or datetime.fromisoformat(prior['lease_until']) <= now(), 'REQUEST_AUDIT_ALREADY_CLAIMED')
- until = (now() + timedelta(seconds=lease_seconds)).isoformat()
- c.execute('INSERT OR REPLACE INTO dispatch_audits VALUES(?,?,?,?,?,?,?,?)',
- (ident, canonical(spec), generation, owner, sha(token.encode()), until, 'CLAIMED', now().isoformat()))
- event(c, ident, 'REQUEST_VERIFICATION_CLAIMED', {'generation': generation, 'dispatchAllowed': False, 'reservedMinor': 0})
- c.commit()
- return {'ok': True, 'intentId': ident, 'generation': generation, 'owner': owner, 'leaseToken': token,
- 'leaseUntil': until, 'dispatchAllowed': False, 'costReservedMinor': 0, 'purpose': 'REQUEST_VERIFICATION_ONLY'}
- def release(root, lease, generation):
- need(isinstance(lease, dict) and lease.get('generation') == generation, 'LIBRARY_VERSION_CHANGED')
- with closing(connect(root, True)) as c:
- row = c.execute('SELECT * FROM dispatch_audits WHERE id=?', (lease.get('intentId'),)).fetchone()
- need(row is not None and row['state'] == 'CLAIMED' and row['owner'] == lease.get('owner') and
- row['generation'] == generation and isinstance(lease.get('leaseToken'), str) and
- secrets.compare_digest(row['token_hash'], sha(lease['leaseToken'].encode())), 'AUDIT_LEASE_MISMATCH')
- need(datetime.fromisoformat(row['lease_until']) > now(), 'AUDIT_LEASE_EXPIRED')
- c.execute('UPDATE dispatch_audits SET state=?,updated_at=? WHERE id=?', ('RELEASED', now().isoformat(), row['id']))
- event(c, row['id'], 'REQUEST_VERIFICATION_RELEASED', {})
- c.commit()
- return {'ok': True, 'dispatchAllowed': False, 'costReservedMinor': 0}
- def projection(root, generation):
- """Redacted read model; no local paths, tokens, owner names or raw account metadata."""
- with closing(connect(root)) as c:
- ready = installed(c)
- summaries = [json.loads(r[0]) for r in c.execute('SELECT summary FROM dispatch_closeouts')] if ready else []
- leases = c.execute('SELECT generation,lease_until,state FROM dispatch_audits').fetchall() if ready else []
- count = c.execute('SELECT count(*) FROM dispatch_history').fetchone()[0] if ready else 0
- from monitoring_ledger import projection as ledger_projection
- ledger = ledger_projection(c)
- active = [r for r in leases if r['state'] == 'CLAIMED' and datetime.fromisoformat(r['lease_until']) > now()]
- return {'installed': ready, **STOP, 'dispatchAllowed': False, 'remainingDispatchMinor': 0,
- 'reservedMinor': 0, 'identifiedSettledRequests': ledger['providedLedgerRows'] if ledger else count,
- 'parameterBoundSettledRequests': ledger['requestSlotBoundRows'] if ledger else count,
- 'ledgerRows': summaries[0]['ledgerRows'] if summaries else None,
- 'aggregateOnlyRows': 0 if ledger else summaries[0]['priorAggregateRows'] if summaries else None,
- 'fullHistoricalIdentitiesVerified': bool(ledger),
- 'providedLedger': ledger,
- 'activeAuditLeases': sum(r['generation'] == generation for r in active),
- 'staleAuditLeases': sum(r['generation'] != generation for r in active),
- 'remoteCollectorsIntegrated': False,
- 'note': '统一请求核对与认领只用于资料复核;154行附件账本已逐条对齐,未绑定参数的行保持未知,不按请求名猜补;不重复加总。远端采集窗口尚未接入。' if ledger else '统一请求核对与认领只用于资料复核;本地76条逐件收费记录与154行总账分列,不重复加总。远端采集窗口尚未接入。'}
|