Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

custom fields: Batch CustomProfileFieldValue reads and writes.

Ahmed Tabisha23b31fe610e
diff --git a/zerver/actions/custom_profile_fields.py b/zerver/actions/custom_profile_fields.py
index 81064559c05..a9760390bef 100644
--- a/zerver/actions/custom_profile_fields.py
+++ b/zerver/actions/custom_profile_fields.py
@@ -206,10 +206,56 @@ def do_update_user_custom_profile_data_if_changed(
) -> None:
changes: list[UserProfileChangeDict] = []
- for custom_profile_field in data:
- field_value, created = CustomProfileFieldValue.objects.get_or_create(
- user_profile=user_profile, field_id=custom_profile_field["id"]
+ field_ids = [custom_profile_field["id"] for custom_profile_field in data]
+
+ existing_field_values_by_field_id = {
+ field_value.field_id: field_value
+ for field_value in CustomProfileFieldValue.objects.filter(
+ user_profile=user_profile, field_id__in=field_ids
+ ).select_related("field")
+ }
+
+ field_values_to_create = [
+ CustomProfileFieldValue(user_profile=user_profile, field=field)
+ for field in CustomProfileField.objects.filter(
+ realm_id=user_profile.realm_id,
+ id__in=[
+ field_id
+ for field_id in field_ids
+ if field_id not in existing_field_values_by_field_id
+ ],
)
+ ]
+ field_ids_to_create = {field_value.field_id for field_value in field_values_to_create}
+
+ if field_values_to_create:
+ # Two requests can both see no existing value for a field and
+ # both attempt to create one; ignore_conflicts lets whichever
+ # request's INSERT lands second be silently skipped instead of
+ # raising IntegrityError on the unique_together(user_profile,
+ # field) constraint. Django doesn't populate the inserted
+ # objects in this mode, so we re-fetch to get the current,
+ # authoritative rows -- which may belong to the other request.
+ CustomProfileFieldValue.objects.bulk_create(field_values_to_create, ignore_conflicts=True)
+ refetched_field_values_by_field_id = {
+ field_value.field_id: field_value
+ for field_value in CustomProfileFieldValue.objects.filter(
+ user_profile=user_profile, field_id__in=field_ids_to_create
+ ).select_related("field")
+ }
+ else:
+ refetched_field_values_by_field_id = {}
+
+ field_values_by_field_id: dict[int, CustomProfileFieldValue] = {
+ **existing_field_values_by_field_id,
+ **refetched_field_values_by_field_id,
+ }
+
+ modified_field_values: list[CustomProfileFieldValue] = []
+
+ for custom_profile_field in data:
+ field_id = custom_profile_field["id"]
+ field_value = field_values_by_field_id[field_id]
# field_value.value is a TextField() so we need to have field["value"]
# in string form to correctly make comparisons and assignments.
@@ -218,7 +264,10 @@ def do_update_user_custom_profile_data_if_changed(
else:
custom_profile_field_value_string = orjson.dumps(custom_profile_field["value"]).decode()
- if not created and field_value.value == custom_profile_field_value_string:
+ if (
+ field_id not in field_ids_to_create
+ and field_value.value == custom_profile_field_value_string
+ ):
# If the field value isn't actually being changed to a different one,
# we have nothing to do here for this field.
continue
@@ -230,9 +279,8 @@ def do_update_user_custom_profile_data_if_changed(
field_value.rendered_value = render_stream_description(
custom_profile_field_value_string, user_profile.realm
)
- field_value.save(update_fields=["value", "rendered_value"])
- else:
- field_value.save(update_fields=["value"])
+ modified_field_values.append(field_value)
+
notify_user_update_custom_profile_data(
user_profile,
{
@@ -253,6 +301,8 @@ def do_update_user_custom_profile_data_if_changed(
)
)
+ CustomProfileFieldValue.objects.bulk_update(modified_field_values, ["value", "rendered_value"])
+
if changes and notify:
send_user_profile_update_notification(
user_profile=user_profile, acting_user=acting_user, changes=changes
diff --git a/zerver/tests/test_custom_profile_data.py b/zerver/tests/test_custom_profile_data.py
index d9aa7fd92d1..62f3301ee7a 100644
--- a/zerver/tests/test_custom_profile_data.py
+++ b/zerver/tests/test_custom_profile_data.py
@@ -7,6 +7,7 @@ from typing_extensions import override
from zerver.actions.custom_profile_fields import (
do_remove_realm_custom_profile_field,
+ do_update_user_custom_profile_data_if_changed,
try_add_realm_custom_profile_field,
try_reorder_realm_custom_profile_fields,
)
@@ -923,7 +924,7 @@ class UpdateCustomProfileFieldTest(CustomProfileFieldTestCase):
)
# Update value of field
- with self.assert_database_query_count(36):
+ with self.assert_database_query_count(13):
result = self.client_patch(
"/json/users/me/profile_data",
{
@@ -961,6 +962,45 @@ class UpdateCustomProfileFieldTest(CustomProfileFieldTestCase):
if field_dict["id"] == field.id:
self.assertEqual(field_dict["value"], "foobar")
+ def test_update_profile_data_handles_concurrent_creation(self) -> None:
+ """
+ Two requests can both observe that a user has no CustomProfileFieldValue for a field
+ and both try to create one; the unique constraint on (user_profile, field) means only
+ one INSERT can succeed. Verify the race is handled.
+ """
+ realm = get_realm("zulip")
+ iago = self.example_user("iago")
+ field = CustomProfileField.objects.get(name="GitHub username", realm=realm)
+ CustomProfileFieldValue.objects.filter(user_profile=iago, field=field).delete()
+
+ real_bulk_create = CustomProfileFieldValue.objects.bulk_create
+
+ def racing_bulk_create(*args: Any, **kwargs: Any) -> Any:
+ # Simulate a concurrent request creating the same row
+ # first, in the window between our own SELECT and this
+ # bulk_create call.
+ CustomProfileFieldValue.objects.create(
+ user_profile=iago, field=field, value="raced-in-value"
+ )
+ return real_bulk_create(*args, **kwargs)
+
+ with mock.patch.object(
+ CustomProfileFieldValue.objects, "bulk_create", side_effect=racing_bulk_create
+ ):
+ do_update_user_custom_profile_data_if_changed(
+ iago,
+ [{"id": field.id, "value": "our-value"}],
+ iago,
+ notify=False,
+ )
+
+ # Verify the request finished gracefully, with one row holding our value.
+ values = CustomProfileFieldValue.objects.filter(user_profile=iago, field=field)
+ self.assertEqual(values.count(), 1)
+ value = values.first()
+ assert value is not None
+ self.assertEqual(value.value, "our-value")
+
def test_update_invalid_dropdown_field(self) -> None:
field_name = "Favorite editor"
self.assert_error_update_invalid_value(