fix: ensure_merchant_roles 热路径快速返回 + gunicorn 6 workers 缓解排队
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -4,6 +4,10 @@ from merchant_ops.models import (
|
||||
MerchantStaffPermission, MerchantStaffRole, MerchantStaffRolePermission,
|
||||
)
|
||||
|
||||
_SYSTEM_ROLE_CODES = {t['role_code'] for t in SYSTEM_ROLE_TEMPLATES}
|
||||
_SYSTEM_BOOTSTRAPPED = False
|
||||
_MERCHANT_BOOTSTRAPPED = set()
|
||||
|
||||
|
||||
def seed_global_permissions():
|
||||
for idx, (code, name) in enumerate(PERMISSION_DEFINITIONS):
|
||||
@@ -23,7 +27,24 @@ def _sync_role_permissions(role, perm_codes):
|
||||
role.role_permissions.exclude(perm_code__in=perm_codes).delete()
|
||||
|
||||
|
||||
def _system_roles_ready():
|
||||
if not _SYSTEM_ROLE_CODES:
|
||||
return False
|
||||
existing = set(
|
||||
MerchantStaffRole.query.filter(
|
||||
merchant_id=None, is_system=True, status=1,
|
||||
).values_list('role_code', flat=True)
|
||||
)
|
||||
if not _SYSTEM_ROLE_CODES <= existing:
|
||||
return False
|
||||
return MerchantStaffPermission.query.count() >= len(PERMISSION_DEFINITIONS)
|
||||
|
||||
|
||||
def ensure_system_role_templates():
|
||||
global _SYSTEM_BOOTSTRAPPED
|
||||
if _SYSTEM_BOOTSTRAPPED or _system_roles_ready():
|
||||
_SYSTEM_BOOTSTRAPPED = True
|
||||
return
|
||||
seed_global_permissions()
|
||||
for tpl in SYSTEM_ROLE_TEMPLATES:
|
||||
role, _ = MerchantStaffRole.objects.get_or_create(
|
||||
@@ -38,10 +59,24 @@ def ensure_system_role_templates():
|
||||
},
|
||||
)
|
||||
_sync_role_permissions(role, tpl['permissions'])
|
||||
_SYSTEM_BOOTSTRAPPED = True
|
||||
|
||||
|
||||
def ensure_merchant_roles(merchant_id):
|
||||
"""为商家复制系统角色模板,并同步预置角色权限。"""
|
||||
"""为商家复制系统角色模板。已初始化则直接返回,避免热路径全量同步拖垮 worker。"""
|
||||
mid = str(merchant_id)
|
||||
if mid in _MERCHANT_BOOTSTRAPPED:
|
||||
return
|
||||
|
||||
existing_codes = set(
|
||||
MerchantStaffRole.query.filter(
|
||||
merchant_id=merchant_id, is_system=True, status=1,
|
||||
).values_list('role_code', flat=True)
|
||||
)
|
||||
if _SYSTEM_ROLE_CODES and _SYSTEM_ROLE_CODES <= existing_codes:
|
||||
_MERCHANT_BOOTSTRAPPED.add(mid)
|
||||
return
|
||||
|
||||
ensure_system_role_templates()
|
||||
templates = MerchantStaffRole.query.filter(merchant_id=None, status=1)
|
||||
for tpl in templates:
|
||||
@@ -58,3 +93,4 @@ def ensure_merchant_roles(merchant_id):
|
||||
)
|
||||
tpl_perms = list(tpl.role_permissions.values_list('perm_code', flat=True))
|
||||
_sync_role_permissions(role, tpl_perms)
|
||||
_MERCHANT_BOOTSTRAPPED.add(mid)
|
||||
|
||||
Reference in New Issue
Block a user