193_group_profit_control_auth_cache_invalidation.sql 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. -- Profit-control fields are part of the API-key auth snapshot and gate the
  2. -- scheduling admission filter; the profit threshold D additionally depends on
  3. -- group pricing and peak-window fields. Extend the durable invalidation
  4. -- trigger so out-of-band group edits (direct SQL, crash between update and
  5. -- app-level invalidation) cannot leave cached snapshots using stale
  6. -- profit-control inputs. Normal admin saves already invalidate via
  7. -- InvalidateAuthCacheByGroupID; this trigger is the durable backstop. Based on
  8. -- the latest function body from 186_group_auth_cache_image_generation.sql.
  9. CREATE OR REPLACE FUNCTION enqueue_group_auth_cache_invalidation()
  10. RETURNS TRIGGER
  11. LANGUAGE plpgsql
  12. AS $$
  13. DECLARE
  14. target_group_id BIGINT;
  15. BEGIN
  16. target_group_id := OLD.id;
  17. IF TG_OP = 'UPDATE'
  18. AND OLD.status IS NOT DISTINCT FROM NEW.status
  19. AND OLD.is_exclusive IS NOT DISTINCT FROM NEW.is_exclusive
  20. AND OLD.allow_image_generation IS NOT DISTINCT FROM NEW.allow_image_generation
  21. AND OLD.platform IS NOT DISTINCT FROM NEW.platform
  22. AND OLD.subscription_type IS NOT DISTINCT FROM NEW.subscription_type
  23. AND OLD.rate_multiplier IS NOT DISTINCT FROM NEW.rate_multiplier
  24. AND OLD.peak_rate_enabled IS NOT DISTINCT FROM NEW.peak_rate_enabled
  25. AND OLD.peak_start IS NOT DISTINCT FROM NEW.peak_start
  26. AND OLD.peak_end IS NOT DISTINCT FROM NEW.peak_end
  27. AND OLD.peak_rate_multiplier IS NOT DISTINCT FROM NEW.peak_rate_multiplier
  28. AND OLD.profit_control_enabled IS NOT DISTINCT FROM NEW.profit_control_enabled
  29. AND OLD.profit_min_margin IS NOT DISTINCT FROM NEW.profit_min_margin
  30. AND OLD.profit_safety_buffer IS NOT DISTINCT FROM NEW.profit_safety_buffer
  31. AND OLD.deleted_at IS NOT DISTINCT FROM NEW.deleted_at THEN
  32. RETURN NEW;
  33. END IF;
  34. INSERT INTO auth_cache_invalidation_outbox (cache_key)
  35. SELECT encode(sha256(convert_to(k.key, 'UTF8')), 'hex')
  36. FROM api_keys AS k
  37. WHERE k.group_id = target_group_id
  38. AND k.deleted_at IS NULL
  39. AND k.key <> '';
  40. IF TG_OP = 'DELETE' THEN
  41. RETURN OLD;
  42. END IF;
  43. RETURN NEW;
  44. END;
  45. $$;