"""Row-lock regressions for real PostgreSQL; never call production services.""" import json import uuid from concurrent.futures import ThreadPoolExecutor from threading import Barrier, Event from django.contrib.auth import get_user_model from django.db import close_old_connections, connection, connections, transaction from django.test import Client, TransactionTestCase, override_settings, skipUnlessDBFeature from django.urls import reverse from django.utils import timezone from control.models import HourlyUsageRecord, Node, NodeReport, NodeTrafficSample, Plan, Subscription, UsageRecord @override_settings(SECURE_SSL_REDIRECT=False) @skipUnlessDBFeature("has_select_for_update") class UsageConcurrencyTests(TransactionTestCase): def setUp(self): user = get_user_model().objects.create_user( username="usage-owner", password="fixture-only", account_status="active" ) plan = Plan.objects.create(name="Usage fixture", slug="usage-fixture", audience=Plan.Audience.ALL) self.subscription = Subscription.objects.create(user=user, plan=plan) self.subscription.activate() self.nodes = [] for index in range(2): node = Node.objects.create( name=f"Fixture {index}", slug=f"usage-node-{index}", server="192.0.2.1", port=11080+index, protocol=Node.Protocol.VLESS_REALITY, status=Node.Status.ONLINE, active=True, subscription_enabled=True, sni="example.invalid", reality_public_key="fixture", reality_short_id="0123456789abcdef", ) node.set_agent_token("node-concurrency-fixture-not-a-real-token") node.save(update_fields=["agent_token_digest"]) self.nodes.append(node) @staticmethod def in_thread(action): close_old_connections() try: return action() finally: connections.close_all() def run_together(self, *actions): barrier = Barrier(len(actions)) def run(action): barrier.wait(timeout=8) return action() with ThreadPoolExecutor(max_workers=len(actions)) as pool: futures = [pool.submit(self.in_thread, lambda action=action: run(action)) for action in actions] return [future.result(timeout=25) for future in futures] def post(self, node, report_id, upload=10, download=20): response = Client().post(reverse("node-sync"), data=json.dumps({ "report_id": str(report_id), "success": True, "applied_subscription_ids": [self.subscription.pk], "usage": [{"subscription_id": self.subscription.pk, "upload_bytes": upload, "download_bytes": download}], }), content_type="application/json", HTTP_X_NODE_SLUG=node.slug, HTTP_AUTHORIZATION="Bearer node-concurrency-fixture-not-a-real-token") return response.status_code, response.json()["status"] def assert_totals(self, upload, download): self.subscription.refresh_from_db() self.assertEqual((self.subscription.upload_bytes, self.subscription.download_bytes), (upload, download)) self.assertEqual(sum(row.upload_bytes for row in UsageRecord.objects.all()), upload) self.assertEqual(sum(row.download_bytes for row in UsageRecord.objects.all()), download) def test_recompute_does_not_overwrite_a_concurrently_committed_node(self): # Writer A holds its subscription update open. B reaches the parent row # while A is still uncommitted. Aggregate-before-lock loses A's delta; # lock-before-aggregate waits and sees A after commit. No timing sleeps. first_ready, second_locks_parent = Event(), Event() def first(): with transaction.atomic(): UsageRecord.objects.create(subscription=self.subscription, node=self.nodes[0], day=timezone.localdate(), upload_bytes=10, download_bytes=20) first_ready.set() self.assertTrue(second_locks_parent.wait(10), "Second writer did not reach the parent lock") def second(): self.assertTrue(first_ready.wait(10)) def observe(execute, sql, params, many, context): upper = sql.upper() if '"CONTROL_SUBSCRIPTION"' in upper and ( upper.startswith("UPDATE") or "FOR UPDATE" in upper or "FOR NO KEY UPDATE" in upper ): second_locks_parent.set() return execute(sql, params, many, context) with connection.execute_wrapper(observe), transaction.atomic(): UsageRecord.objects.create(subscription=self.subscription, node=self.nodes[1], day=timezone.localdate(), upload_bytes=30, download_bytes=40) self.run_together(first, second) self.assert_totals(40, 60) def test_simultaneous_duplicate_report_is_billed_once(self): report_id = uuid.uuid4() results = self.run_together(*(lambda: self.post(self.nodes[0], report_id) for _ in range(3))) self.assertEqual(sorted(results), [(200, "accepted"), (200, "already_processed"), (200, "already_processed")]) self.assert_totals(10, 20) self.assertEqual((NodeReport.objects.count(), NodeTrafficSample.objects.count()), (1, 1)) self.assertEqual(HourlyUsageRecord.objects.get().download_bytes, 20) def test_distinct_first_reports_same_node_do_not_lose_or_duplicate_usage(self): results = self.run_together(*(lambda: self.post(self.nodes[0], uuid.uuid4()) for _ in range(3))) self.assertEqual(results, [(200, "accepted")] * 3) self.assert_totals(30, 60) self.assertEqual((NodeReport.objects.count(), NodeTrafficSample.objects.count()), (3, 3)) self.assertEqual(HourlyUsageRecord.objects.get().download_bytes, 60) self.nodes[0].refresh_from_db() self.assertEqual(self.nodes[0].total_download_bytes, 60) def test_different_nodes_accumulate_into_one_subscription(self): results = self.run_together(*(lambda node=node: self.post(node, uuid.uuid4()) for node in self.nodes)) self.assertEqual(results, [(200, "accepted")] * 2) self.assert_totals(20, 40) self.assertEqual(HourlyUsageRecord.objects.count(), 2) self.assertEqual(sum(row.download_bytes for row in HourlyUsageRecord.objects.all()), 40)