43 lines
2.0 KiB
Python
43 lines
2.0 KiB
Python
|
|
"""Opt-in integration and database runtime switch. No implicit activation."""
|
||
|
|
import json
|
||
|
|
import logging
|
||
|
|
from app.core.config import settings
|
||
|
|
from app.core.database import execute_query_single, execute_update
|
||
|
|
|
||
|
|
logger = logging.getLogger(__name__)
|
||
|
|
|
||
|
|
|
||
|
|
def active_for_customer(customer_id):
|
||
|
|
if not settings.WORKFLOWS_ENABLED or settings.WORKFLOWS_MODE != 'active':
|
||
|
|
return False
|
||
|
|
if customer_id is None:
|
||
|
|
return settings.WORKFLOWS_INTERNAL_ENABLED
|
||
|
|
return int(customer_id) in settings.WORKFLOWS_CUSTOMER_IDS
|
||
|
|
|
||
|
|
|
||
|
|
def configure_runtime():
|
||
|
|
"""Synchronize the opt-in switch before workers start; tolerate an unmigrated database when disabled."""
|
||
|
|
# A migrated database may retain its enabled flag after a previous run.
|
||
|
|
exists = execute_query_single("SELECT to_regclass('public.bmc_workflow_runtime') AS name")
|
||
|
|
if not exists or not exists.get('name'):
|
||
|
|
if settings.WORKFLOWS_ENABLED:
|
||
|
|
raise RuntimeError('Workflow migrations must be applied before enabling workflows')
|
||
|
|
return
|
||
|
|
if settings.WORKFLOWS_MODE not in {'shadow', 'active'}:
|
||
|
|
raise RuntimeError('WORKFLOWS_MODE must be shadow or active')
|
||
|
|
if settings.WORKFLOWS_ENABLED and settings.WORKFLOWS_MODE == 'active' and not settings.WORKFLOWS_CUSTOMER_IDS and not settings.WORKFLOWS_INTERNAL_ENABLED:
|
||
|
|
raise RuntimeError('Active workflows require an explicit customer allowlist')
|
||
|
|
execute_update("UPDATE bmc_workflow_runtime SET enabled=%s, mode=%s, customer_ids=%s::jsonb, internal_enabled=%s, updated_at=now() WHERE id=1",
|
||
|
|
(settings.WORKFLOWS_ENABLED, settings.WORKFLOWS_MODE, json.dumps(settings.WORKFLOWS_CUSTOMER_IDS), settings.WORKFLOWS_INTERNAL_ENABLED))
|
||
|
|
|
||
|
|
|
||
|
|
def run_workflow_jobs():
|
||
|
|
if not settings.WORKFLOWS_ENABLED:
|
||
|
|
return
|
||
|
|
from .worker import process_pending_events
|
||
|
|
try:
|
||
|
|
return process_pending_events(limit=20, mode=settings.WORKFLOWS_MODE,
|
||
|
|
customer_ids=settings.WORKFLOWS_CUSTOMER_IDS)
|
||
|
|
except Exception:
|
||
|
|
logger.exception('Workflow queue processing failed')
|