manage-industry-pipeline.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. """Manage receipt-driven pagination and due observation slots; no upstream network or billing."""
  2. import argparse
  3. import os
  4. import json
  5. from pathlib import Path
  6. import signal
  7. import sys
  8. import time
  9. import uuid
  10. ROOT = Path(__file__).resolve().parents[1]
  11. sys.path.insert(0, str(ROOT / 'server/voc-library'))
  12. from industry_monitor import load, Monitor
  13. from monitoring_pipeline import (connection, export_cycle, finalize, now, projection, receive, schedule,
  14. seed_registered, setup, tick)
  15. from contextlib import closing
  16. from monitoring_inbox import consume
  17. def main():
  18. p = argparse.ArgumentParser(description=__doc__)
  19. p.add_argument('command', choices=['seed', 'status', 'receive', 'finalize', 'draft', 'schedule', 'tick', 'inbox'])
  20. sources = p.add_mutually_exclusive_group(required=not bool(os.environ.get('KSF_UNIFIED_DB_CONFIG')))
  21. sources.add_argument('--snapshot')
  22. sources.add_argument('--registry')
  23. sources.add_argument('--db')
  24. p.add_argument('--store', required=True)
  25. p.add_argument('--generation', required=True)
  26. p.add_argument('--manifest', type=Path)
  27. p.add_argument('--cycle-id')
  28. p.add_argument('--inbox', type=Path)
  29. p.add_argument('--interval', type=int, default=10)
  30. p.add_argument('--watch', action='store_true')
  31. p.add_argument('--interval-seconds', type=int)
  32. p.add_argument('--first-due')
  33. p.add_argument('--page', type=int, default=1)
  34. p.add_argument('--out', type=Path)
  35. args = p.parse_args()
  36. config = {k: getattr(args, k) for k in ('snapshot', 'registry', 'db') if getattr(args, k)}
  37. def bound():
  38. data = load(config)
  39. if data['generation'] != args.generation:
  40. raise ValueError('LIBRARY_VERSION_CHANGED')
  41. return Monitor(data)
  42. monitor = bound()
  43. if args.watch and args.command != 'inbox':
  44. raise ValueError('WATCH_REQUIRES_INBOX')
  45. if args.command == 'seed':
  46. result = seed_registered(args.store, args.generation)
  47. elif args.command == 'status':
  48. result = {'ok': True, **projection(args.store, args.generation, {}, set(monitor.products), args.page)}
  49. elif args.command in ('receive', 'schedule'):
  50. if not args.manifest:
  51. raise ValueError('MANIFEST_REQUIRED')
  52. manifest = json.loads(args.manifest.read_text('utf-8-sig'))
  53. if manifest.get('generation') != args.generation:
  54. raise ValueError('PIPELINE_GENERATION_CHANGED')
  55. if args.command == 'receive':
  56. result = receive(args.store, manifest, args.manifest.resolve().parent)
  57. else:
  58. result = schedule(args.store, manifest, args.interval_seconds, args.first_due)
  59. elif args.command == 'finalize':
  60. result = finalize(args.store, args.cycle_id, args.generation)
  61. elif args.command == 'draft':
  62. from monitoring_pipeline import request_candidate
  63. _, row, assessment = export_cycle(args.store, args.cycle_id, args.generation)
  64. result = {'ok': True, 'cycleId': args.cycle_id,
  65. 'nextRequest': request_candidate(json.loads(row['specification']), assessment),
  66. 'dispatchEnabled': False}
  67. elif args.command == 'tick':
  68. result = tick(args.store, args.generation)
  69. else:
  70. if not args.inbox:
  71. raise ValueError('INBOX_REQUIRED')
  72. if not 2 <= args.interval <= 60:
  73. raise ValueError('INVALID_INBOX_POLL_INTERVAL')
  74. running = True
  75. def stop(_signal, _frame):
  76. nonlocal running
  77. running = False
  78. signal.signal(signal.SIGINT, stop)
  79. signal.signal(signal.SIGTERM, stop)
  80. worker_id = uuid.uuid4().hex
  81. setup(args.store)
  82. try:
  83. while running:
  84. bound() # A production library switch stops the old-generation worker.
  85. if args.watch:
  86. with closing(connection(args.store)) as c:
  87. c.execute('INSERT OR REPLACE INTO pipeline_workers VALUES(?,?,?,?,?)', (worker_id, args.generation, now(), args.interval, 'WATCHING'))
  88. c.commit()
  89. result = consume(args.store, args.inbox, args.generation)
  90. if not args.watch:
  91. break
  92. # Local receipt changes only; quiet while the inbox is unchanged.
  93. if result['accepted'] or result['rejected']:
  94. print(json.dumps(result, ensure_ascii=False), flush=True)
  95. deadline = time.monotonic() + args.interval
  96. while running and time.monotonic() < deadline:
  97. time.sleep(min(.25, max(0, deadline - time.monotonic())))
  98. finally:
  99. if args.watch:
  100. with closing(connection(args.store)) as c:
  101. c.execute('UPDATE pipeline_workers SET state=?,heartbeat=? WHERE id=?', ('STOPPED', now(), worker_id))
  102. c.commit()
  103. if args.out:
  104. with args.out.open('x', encoding='utf-8') as stream:
  105. json.dump(result, stream, ensure_ascii=False, indent=2)
  106. stream.write('\n')
  107. print(json.dumps(result, ensure_ascii=False))
  108. if __name__ == '__main__':
  109. try:
  110. main()
  111. except Exception as exc:
  112. import re
  113. code = str(exc) if isinstance(exc, ValueError) and re.fullmatch('[A-Z][A-Z0-9_]+', str(exc)) else 'PIPELINE_OPERATION_FAILED'
  114. print(json.dumps({'ok': False, 'error': code, 'paidCalls': 0, 'dispatchEnabled': False}))
  115. sys.exit(1)