Repository: wagtail/wagtail

Issue:
Race condition with new page subscriptions
### Issue Summary

If an editor visits the EditView for a page which they have not accessed before, a subscription is created. However if two processes take this request at the same time, there's a risk that a subscription already exists and a 500 error occurs:

```
Internal Server Error: /admin/pages/64/edit/
Traceback (most recent call last):
  File "/Users/tomkins/.virtualenvs/bakerydemo/lib/python3.11/site-packages/django/db/backends/utils.py", line 89, in _execute
    return self.cursor.execute(sql, params)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/tomkins/.virtualenvs/bakerydemo/lib/python3.11/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute
    return super().execute(query, params)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
sqlite3.IntegrityError: UNIQUE constraint failed: wagtailcore_pagesubscription.page_id, wagtailcore_pagesubscription.user_id

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/Users/tomkins/.virtualenvs/bakerydemo/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "/Users/tomkins/.virtualenvs/bakerydemo/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/tomkins/.virtualenvs/bakerydemo/lib/python3.11/site-packages/django/views/decorators/cache.py", line 62, in _wrapper_view_func
    response = view_func(request, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/tomkins/.virtualenvs/bakerydemo/lib/python3.11/site-packages/wagtail/admin/urls/__init__.py", line 180, in wrapper
    return view_func(request, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/tomkins/.virtualenvs/bakerydemo/lib/python3.11/site-packages/wagtail/admin/auth.py", line 165, in decorated_view
    response = view_func(request, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/tomkins/.virtualenvs/bakerydemo/lib/python3.11/site-packages/django/views/generic/base.py", line 104, in view
    return self.dispatch(request, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/tomkins/.virtualenvs/bakerydemo/lib/python3.11/site-packages/wagtail/admin/views/pages/edit.py", line 386, in dispatch
    return super().dispatch(request)
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/tomkins/.virtualenvs/bakerydemo/lib/python3.11/site-packages/django/views/generic/base.py", line 143, in dispatch
    return handler(request, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/tomkins/.virtualenvs/bakerydemo/lib/python3.11/site-packages/wagtail/admin/views/pages/edit.py", line 470, in post
    return self.form_valid(self.form)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/tomkins/.virtualenvs/bakerydemo/lib/python3.11/site-packages/wagtail/admin/views/pages/edit.py", line 496, in form_valid
    return self.publish_action()
           ^^^^^^^^^^^^^^^^^^^^^
  File "/Users/tomkins/.virtualenvs/bakerydemo/lib/python3.11/site-packages/wagtail/admin/views/pages/edit.py", line 546, in publish_action
    self.subscription.save()
  File "/Users/tomkins/.virtualenvs/bakerydemo/lib/python3.11/site-packages/django/db/models/base.py", line 814, in save
    self.save_base(
  File "/Users/tomkins/.virtualenvs/bakerydemo/lib/python3.11/site-packages/django/db/models/base.py", line 877, in save_base
    updated = self._save_table(
              ^^^^^^^^^^^^^^^^^
  File "/Users/tomkins/.virtualenvs/bakerydemo/lib/python3.11/site-packages/django/db/models/base.py", line 1020, in _save_table
    results = self._do_insert(
              ^^^^^^^^^^^^^^^^
  File "/Users/tomkins/.virtualenvs/bakerydemo/lib/python3.11/site-packages/django/db/models/base.py", line 1061, in _do_insert
    return manager._insert(
           ^^^^^^^^^^^^^^^^
  File "/Users/tomkins/.virtualenvs/bakerydemo/lib/python3.11/site-packages/django/db/models/manager.py", line 87, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/tomkins/.virtualenvs/bakerydemo/lib/python3.11/site-packages/django/db/models/query.py", line 1805, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/tomkins/.virtualenvs/bakerydemo/lib/python3.11/site-packages/django/db/models/sql/compiler.py", line 1822, in execute_sql
    cursor.execute(sql, params)
  File "/Users/tomkins/.virtualenvs/bakerydemo/lib/python3.11/site-packages/django/db/backends/utils.py", line 67, in execute
    return self._execute_with_wrappers(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/tomkins/.virtualenvs/bakerydemo/lib/python3.11/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers
    return executor(sql, params, many, context)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/tomkins/.virtualenvs/bakerydemo/lib/python3.11/site-packages/django/db/backends/utils.py", line 84, in _execute
    with self.db.wrap_database_errors:
  File "/Users/tomkins/.virtualenvs/bakerydemo/lib/python3.11/site-packages/django/db/utils.py", line 91, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/Users/tomkins/.virtualenvs/bakerydemo/lib/python3.11/site-packages/django/db/backends/utils.py", line 89, in _execute
    return self.cursor.execute(sql, params)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/tomkins/.virtualenvs/bakerydemo/lib/python3.11/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute
    return super().execute(query, params)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```

### Steps to Reproduce

Slightly tricky, I only found this through benchmarking Wagtail on SQLite: https://github.com/tomkins/wagtail-sqlite-benchmark.

Using 8 editor threads the result ends up with the above exception, and the following report from Locust:

```
Error report
# occurrences      Error
------------------|-----------------------------------------------------------------------------------------------------------------------------------
1                  POST /admin/pages/[locations.LocationPage]/edit/: BadStatusCode('http://127.0.0.1:8000/admin/pages/67/edit/', code=500)
------------------|-----------------------------------------------------------------------------------------------------------------------------------
```

-   I have confirmed that this issue can be reproduced as described on a fresh Wagtail project: yes

### Technical details

-   Python version: 3.10 (any)
-   Django version: 4.2 (any)
-   Wagtail version: 5.1 (any)
-   Browser version: n/a


Discussion:

Resolving patch:
diff --git a/wagtail/admin/views/pages/edit.py b/wagtail/admin/views/pages/edit.py
--- a/wagtail/admin/views/pages/edit.py
+++ b/wagtail/admin/views/pages/edit.py
@@ -376,14 +376,13 @@ def dispatch(self, request, page_id):
         if response:
             return response
 
-        try:
-            self.subscription = PageSubscription.objects.get(
-                page=self.page, user=self.request.user
-            )
-        except PageSubscription.DoesNotExist:
-            self.subscription = PageSubscription(
-                page=self.page, user=self.request.user, comment_notifications=False
-            )
+        self.subscription, created = PageSubscription.objects.get_or_create(
+            page=self.page,
+            user=self.request.user,
+            defaults={
+                "comment_notifications": False,
+            },
+        )
 
         self.edit_handler = self.page_class.get_edit_handler()
         self.form_class = self.edit_handler.get_form_class()


Test patch:
diff --git a/wagtail/admin/tests/pages/test_edit_page.py b/wagtail/admin/tests/pages/test_edit_page.py
--- a/wagtail/admin/tests/pages/test_edit_page.py
+++ b/wagtail/admin/tests/pages/test_edit_page.py
@@ -3105,6 +3105,11 @@ def test_commment_notifications_switched_off(self):
             response,
             '<input type="checkbox" name="comment_notifications" id="id_comment_notifications">',
         )
+        self.assertTrue(
+            PageSubscription.objects.filter(
+                page=self.child_page, user=self.user, comment_notifications=False
+            ).exists()
+        )
 
     def test_commment_notifications_switched_on(self):
         PageSubscription.objects.create(