135 lines
4.7 KiB
Python
135 lines
4.7 KiB
Python
import threading
|
|
import logging
|
|
from django.db import models
|
|
from django.db.models.signals import pre_save, post_save
|
|
from django.dispatch import receiver
|
|
from .models import FlowDefinition, FlowExecutionLog
|
|
from .engine import execute_flow_dag
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# Thread-local storage for re-entrancy tracking and prior record state
|
|
_thread_locals = threading.local()
|
|
|
|
def _get_active_flow_depth():
|
|
return getattr(_thread_locals, 'active_flow_depth', 0)
|
|
|
|
def _set_active_flow_depth(val):
|
|
_thread_locals.active_flow_depth = val
|
|
|
|
def _get_system_user():
|
|
from django.contrib.auth.models import User
|
|
admin = User.objects.filter(is_superuser=True).order_by('id').first()
|
|
if not admin:
|
|
admin, _ = User.objects.get_or_create(
|
|
username='system_internal',
|
|
defaults={'is_superuser': True, 'is_staff': True}
|
|
)
|
|
return admin
|
|
|
|
MAX_SIGNAL_REENTRANCY_DEPTH = 1
|
|
|
|
def dispatch_flow(flow, context=None, idempotency_key=None, user=None):
|
|
"""
|
|
Dispatches a single flow execution with the given context and user principal.
|
|
"""
|
|
if context is None:
|
|
context = {}
|
|
exec_user = user or getattr(flow, 'created_by', None)
|
|
return execute_flow_dag(flow, initial_context=context, idempotency_key=idempotency_key, user=exec_user)
|
|
|
|
def snapshot_model(instance):
|
|
data = {}
|
|
if hasattr(instance, '__dict__'):
|
|
for k, v in instance.__dict__.items():
|
|
if not k.startswith('_') and isinstance(v, (str, int, float, bool, dict, list)):
|
|
data[k] = v
|
|
if 'id' not in data and getattr(instance, 'id', None):
|
|
data['id'] = instance.id
|
|
if 'name' not in data and hasattr(instance, 'name'):
|
|
data['name'] = instance.name
|
|
return data
|
|
|
|
@receiver(pre_save)
|
|
def on_record_pre_save(sender, instance, **kwargs):
|
|
app_label = sender._meta.app_label
|
|
if app_label not in ('crm_core', 'custom_objects'):
|
|
return
|
|
if sender.__name__ in ('FlowDefinition', 'FlowExecutionLog'):
|
|
return
|
|
|
|
if instance.pk:
|
|
try:
|
|
old_inst = sender.objects.filter(pk=instance.pk).first()
|
|
if old_inst:
|
|
instance._prior_state = snapshot_model(old_inst)
|
|
else:
|
|
instance._prior_state = {}
|
|
except Exception:
|
|
instance._prior_state = {}
|
|
else:
|
|
instance._prior_state = {}
|
|
|
|
@receiver(post_save)
|
|
def on_record_post_save(sender, instance, created, **kwargs):
|
|
app_label = sender._meta.app_label
|
|
if app_label not in ('crm_core', 'custom_objects'):
|
|
return
|
|
if sender.__name__ in ('FlowDefinition', 'FlowExecutionLog'):
|
|
return
|
|
|
|
depth = _get_active_flow_depth()
|
|
if depth >= MAX_SIGNAL_REENTRANCY_DEPTH:
|
|
logger.warning(
|
|
f"Re-entrancy guard blocked flow dispatch for {instance.__class__.__name__} "
|
|
f"(depth {depth} >= {MAX_SIGNAL_REENTRANCY_DEPTH})"
|
|
)
|
|
return
|
|
|
|
trigger_type = 'record_created' if created else 'record_updated'
|
|
model_name = sender.__name__
|
|
|
|
flows = FlowDefinition.objects.filter(
|
|
is_active=True,
|
|
trigger_type=trigger_type,
|
|
trigger_object=model_name
|
|
)
|
|
|
|
if not flows.exists():
|
|
flows = FlowDefinition.objects.filter(
|
|
is_active=True,
|
|
trigger_type=trigger_type,
|
|
trigger_object__iexact=model_name
|
|
)
|
|
|
|
# Scope flows to the record's owner/creator if multi-tenancy applies
|
|
owner = getattr(instance, 'owner', None) or getattr(instance, 'created_by', None)
|
|
if owner and hasattr(FlowDefinition, 'created_by'):
|
|
flows = flows.filter(models.Q(created_by=owner) | models.Q(created_by__isnull=True))
|
|
elif hasattr(FlowDefinition, 'created_by'):
|
|
flows = flows.filter(created_by__isnull=True)
|
|
|
|
current_state = snapshot_model(instance)
|
|
prior_state = getattr(instance, '_prior_state', {})
|
|
|
|
context = {
|
|
'$Record': current_state,
|
|
'$Record__Prior': prior_state,
|
|
'record_id': instance.pk,
|
|
'record_type': model_name,
|
|
'trigger': trigger_type
|
|
}
|
|
|
|
_set_active_flow_depth(depth + 1)
|
|
try:
|
|
for flow in flows:
|
|
# Under Salesforce transactional contract (docs/SALESFORCE_FLOW_ENGINE_SPEC.md:108),
|
|
# an unhandled failure in a synchronous record-triggered flow must fail
|
|
# the transaction and roll back the triggering record modification.
|
|
exec_user = getattr(flow, 'created_by', None) or owner
|
|
# If flow has no owner and record has no owner (e.g. system seed), use system execution identity
|
|
if not exec_user:
|
|
exec_user = _get_system_user()
|
|
dispatch_flow(flow, context=context, user=exec_user)
|
|
finally:
|
|
_set_active_flow_depth(depth)
|