Files
canina/scripts/content-research/consumer.py
T
2026-10-28 08:02:30 +00:00

148 lines
7.0 KiB
Python

"""Dormant NEW-only publisher boundary. Never invokes a publisher on its own."""
import hashlib
import json
import sqlite3
import urllib.request
import urllib.error
BASE = '/api/admin/seo-tracking'
class Blocked(RuntimeError):
pass
def digest(value):
return hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False,
separators=(',', ':')).encode()).hexdigest()
class AdminTransport:
"""Use approved short-lived bearer supplied by caller; no retry or secret logging."""
def __init__(self, origin, bearer):
if not origin.startswith('https://'):
raise ValueError('HTTPS Admin origin required')
self.origin, self.bearer = origin.rstrip('/'), bearer
def __call__(self, method, path, body=None):
if path != BASE and not path.startswith(BASE + '/'):
raise ValueError('Research endpoints only')
request = urllib.request.Request(
self.origin + path, method=method,
data=None if body is None else json.dumps(body).encode(),
headers={'Authorization': 'Bearer ' + self.bearer,
'Content-Type': 'application/json'})
# Never forward Authorization to redirects, even same-origin redirects.
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args, **kwargs):
return None
try:
with urllib.request.build_opener(NoRedirect).open(request, timeout=30) as response:
return json.load(response)
except urllib.error.HTTPError as error:
raise Blocked('Admin HTTP ' + str(error.code)) from None
class Consumer:
def __init__(self, path, api):
self.path, self.api = path, api
with self.db() as db:
db.execute('CREATE TABLE IF NOT EXISTS runs (run TEXT PRIMARY KEY, state TEXT NOT NULL, finding TEXT, packet TEXT, draft_hash TEXT, review TEXT, blog TEXT)')
def db(self):
db = sqlite3.connect(self.path, timeout=10)
db.row_factory = sqlite3.Row
return db
def row(self, run):
with self.db() as db:
row = db.execute('SELECT * FROM runs WHERE run=?', (run,)).fetchone()
if row is None:
raise Blocked('Research must be saved before drafting')
return dict(row)
def prepare(self, run, research):
with self.db() as db:
try:
db.execute('INSERT INTO runs(run,state) VALUES (?,?)', (run, 'research_intent'))
except sqlite3.IntegrityError:
row = self.row(run)
if row['state'] == 'prepared':
return json.loads(row['packet'])
raise Blocked('Existing research intent/outcome requires reconciliation') from None
# Persist intent before POST: timeout must never cause duplicate research.
finding = self.api('POST', BASE, research)
packet = self.api('GET', BASE + '/' + finding['id'])
self.check_packet(packet)
with self.db() as db:
db.execute('UPDATE runs SET state=?,finding=?,packet=? WHERE run=?',
('prepared', packet['id'], json.dumps(packet), run))
return packet
@staticmethod
def check_packet(packet):
for key in ('version', 'feedbackVersion'):
if type(packet.get(key)) is not int or packet[key] < 0:
raise Blocked('Missing directive version')
if not isinstance(packet.get('id'), str) or not packet['id']:
raise Blocked('Missing finding identity')
if packet.get('ceoFeedback') is not None and not isinstance(packet['ceoFeedback'], str):
raise Blocked('Invalid directive')
def publish(self, run, packet, draft, review, publication_preflight):
"""Caller must preserve existing ownership/QA/backup/quota/intent guards.
packet is the complete research/directive supplied to Content before drafting.
review is an independent exact-hash receipt, NOT semantic-compliance proof.
"""
row = self.row(run)
if row['packet'] is None or digest(json.loads(row['packet'])) != digest(packet):
raise Blocked('Packet differs from saved directive')
if row['state'] == 'linked':
return row['blog']
if row['state'] != 'prepared':
raise Blocked('In-flight/ambiguous action: reconcile, never recreate')
self.check_packet(packet)
if packet.get('ceoFeedback', None):
if not isinstance(review, dict) or not review.get('reviewer') or not review.get('evidence') or review.get('directiveHash') != digest(packet) or review.get('draftHash') != digest(draft):
raise Blocked('Exact directive/draft independent review evidence required')
with self.db() as db:
changed = db.execute('UPDATE runs SET state=?,draft_hash=?,review=? WHERE run=? AND state=?',
('claiming', digest(draft), json.dumps(review), run, 'prepared')).rowcount
if changed != 1:
raise Blocked('Another consumer owns action')
# Preflight MUST preserve existing ownership/QA/backup/quota/intent
# guards, but must NOT create a Blog. Only this atomic endpoint writes.
reviewed_hash = digest(draft)
payload = publication_preflight(draft)
if not isinstance(payload, dict) or digest(payload) != reviewed_hash:
raise Blocked('Preflight must return the exact reviewed Blog payload')
with self.db() as db:
db.execute('UPDATE runs SET state=? WHERE run=?', ('publication_intent', run))
result = self.api('POST', BASE + '/' + packet['id'] + '/publication',
dict(expectedVersion=packet['version'],
feedbackVersion=packet['feedbackVersion'], actionId=run, blog=payload))
blog = result.get('blog', {}).get('id')
if (not isinstance(blog, str) or not blog or
result.get('consumedFeedbackVersion') != packet['feedbackVersion']):
raise Blocked('Missing committed publication identity; reconcile, never retry')
with self.db() as db:
db.execute('UPDATE runs SET state=?,blog=? WHERE run=?', ('linked', blog, run))
return blog
def reconcile_link(self, run):
"""Read-only repair of an ambiguous response; never creates or relinks."""
row = self.row(run)
if row['state'] == 'linked':
return row['blog']
if row['state'] != 'publication_intent':
raise Blocked('No publication intent; independent reconciliation required')
current = self.api('GET', BASE + '/' + row['finding'])
self.check_packet(current)
if current.get('actionId') != run or not current.get('blogId'):
raise Blocked('No matching committed action; never retry automatically')
with self.db() as db:
db.execute('UPDATE runs SET state=?,blog=? WHERE run=?',
('linked', current['blogId'], run))
return current['blogId']