| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- """Manage receipt-driven pagination and due observation slots; no upstream network or billing."""
- import argparse
- import os
- import json
- from pathlib import Path
- import signal
- import sys
- import time
- import uuid
- ROOT = Path(__file__).resolve().parents[1]
- sys.path.insert(0, str(ROOT / 'server/voc-library'))
- from industry_monitor import load, Monitor
- from monitoring_pipeline import (connection, export_cycle, finalize, now, projection, receive, schedule,
- seed_registered, setup, tick)
- from contextlib import closing
- from monitoring_inbox import consume
- def main():
- p = argparse.ArgumentParser(description=__doc__)
- p.add_argument('command', choices=['seed', 'status', 'receive', 'finalize', 'draft', 'schedule', 'tick', 'inbox'])
- sources = p.add_mutually_exclusive_group(required=not bool(os.environ.get('KSF_UNIFIED_DB_CONFIG')))
- sources.add_argument('--snapshot')
- sources.add_argument('--registry')
- sources.add_argument('--db')
- p.add_argument('--store', required=True)
- p.add_argument('--generation', required=True)
- p.add_argument('--manifest', type=Path)
- p.add_argument('--cycle-id')
- p.add_argument('--inbox', type=Path)
- p.add_argument('--interval', type=int, default=10)
- p.add_argument('--watch', action='store_true')
- p.add_argument('--interval-seconds', type=int)
- p.add_argument('--first-due')
- p.add_argument('--page', type=int, default=1)
- p.add_argument('--out', type=Path)
- args = p.parse_args()
- config = {k: getattr(args, k) for k in ('snapshot', 'registry', 'db') if getattr(args, k)}
- def bound():
- data = load(config)
- if data['generation'] != args.generation:
- raise ValueError('LIBRARY_VERSION_CHANGED')
- return Monitor(data)
- monitor = bound()
- if args.watch and args.command != 'inbox':
- raise ValueError('WATCH_REQUIRES_INBOX')
- if args.command == 'seed':
- result = seed_registered(args.store, args.generation)
- elif args.command == 'status':
- result = {'ok': True, **projection(args.store, args.generation, {}, set(monitor.products), args.page)}
- elif args.command in ('receive', 'schedule'):
- if not args.manifest:
- raise ValueError('MANIFEST_REQUIRED')
- manifest = json.loads(args.manifest.read_text('utf-8-sig'))
- if manifest.get('generation') != args.generation:
- raise ValueError('PIPELINE_GENERATION_CHANGED')
- if args.command == 'receive':
- result = receive(args.store, manifest, args.manifest.resolve().parent)
- else:
- result = schedule(args.store, manifest, args.interval_seconds, args.first_due)
- elif args.command == 'finalize':
- result = finalize(args.store, args.cycle_id, args.generation)
- elif args.command == 'draft':
- from monitoring_pipeline import request_candidate
- _, row, assessment = export_cycle(args.store, args.cycle_id, args.generation)
- result = {'ok': True, 'cycleId': args.cycle_id,
- 'nextRequest': request_candidate(json.loads(row['specification']), assessment),
- 'dispatchEnabled': False}
- elif args.command == 'tick':
- result = tick(args.store, args.generation)
- else:
- if not args.inbox:
- raise ValueError('INBOX_REQUIRED')
- if not 2 <= args.interval <= 60:
- raise ValueError('INVALID_INBOX_POLL_INTERVAL')
- running = True
- def stop(_signal, _frame):
- nonlocal running
- running = False
- signal.signal(signal.SIGINT, stop)
- signal.signal(signal.SIGTERM, stop)
- worker_id = uuid.uuid4().hex
- setup(args.store)
- try:
- while running:
- bound() # A production library switch stops the old-generation worker.
- if args.watch:
- with closing(connection(args.store)) as c:
- c.execute('INSERT OR REPLACE INTO pipeline_workers VALUES(?,?,?,?,?)', (worker_id, args.generation, now(), args.interval, 'WATCHING'))
- c.commit()
- result = consume(args.store, args.inbox, args.generation)
- if not args.watch:
- break
- # Local receipt changes only; quiet while the inbox is unchanged.
- if result['accepted'] or result['rejected']:
- print(json.dumps(result, ensure_ascii=False), flush=True)
- deadline = time.monotonic() + args.interval
- while running and time.monotonic() < deadline:
- time.sleep(min(.25, max(0, deadline - time.monotonic())))
- finally:
- if args.watch:
- with closing(connection(args.store)) as c:
- c.execute('UPDATE pipeline_workers SET state=?,heartbeat=? WHERE id=?', ('STOPPED', now(), worker_id))
- c.commit()
- if args.out:
- with args.out.open('x', encoding='utf-8') as stream:
- json.dump(result, stream, ensure_ascii=False, indent=2)
- stream.write('\n')
- print(json.dumps(result, ensure_ascii=False))
- if __name__ == '__main__':
- try:
- main()
- except Exception as exc:
- import re
- code = str(exc) if isinstance(exc, ValueError) and re.fullmatch('[A-Z][A-Z0-9_]+', str(exc)) else 'PIPELINE_OPERATION_FAILED'
- print(json.dumps({'ok': False, 'error': code, 'paidCalls': 0, 'dispatchEnabled': False}))
- sys.exit(1)
|