-
-
Notifications
You must be signed in to change notification settings - Fork 218
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
check_repeaters()
task iterates repeaters
#34946
Closed
Closed
Changes from 25 commits
Commits
Show all changes
39 commits
Select commit
Hold shift + click to select a range
5a0e77a
Drop soft asserts
kaapstorm 127912c
Add TODOs
kaapstorm f2b3aa0
`check_repeaters()` uses `iter_ready_repeaters()`
kaapstorm 1267f51
Test `iter_ready_repeaters()`
kaapstorm 1714f62
`process_repeater()` task
kaapstorm c6f603b
Update tests
kaapstorm 3d40f91
Add tests
kaapstorm 3d4e4cd
TestIterReadyRepeater extends SimpleTestCase
kaapstorm d90a5c1
Fix TestUpdateRepeater
kaapstorm 86f1cce
Explain the purpose of MAX_REPEATER_WORKERS
kaapstorm 3315c45
Update TestAppStructureRepeater test
kaapstorm 7c4e3cf
Fix repeater locking
kaapstorm a916c34
Drop repeater lock
kaapstorm bb17648
Don't retry payload errors
kaapstorm 3047c08
Fix `RepeatRecord.count_overdue()`
kaapstorm 5370a17
Some client errors need a retry
kaapstorm f2f50e9
Polling overdue every 5 minutes seems enough
kaapstorm 976d297
Improve query by filtering domains
kaapstorm a922568
Add metric for one loop over repeaters
kaapstorm 1bdca83
Merge branch 'master' into nh/iter_repeaters
kaapstorm 6458b3e
Index filtered fields, add `max_workers`
kaapstorm 369c96e
A partial implementation of a lock using Postgres
kaapstorm 74e6676
Lock repeater
kaapstorm 5e4fbca
Add InvalidPayload state
kaapstorm 5fe6d3c
Make repeat_record.state explicit
kaapstorm 407d60d
Fix tests
kaapstorm 7a02d6a
Revert "Lock repeater"
kaapstorm 62369a4
Revert "A partial implementation of a lock using Postgres"
kaapstorm 2bb7c59
Use Redis Lock
kaapstorm 7d5abeb
Round-robin repeaters by domain
kaapstorm b8543a8
Skip rate-limited repeaters
kaapstorm 2600e94
Make response status clearer
kaapstorm 1b0306a
Use automatic rollback
kaapstorm d333eeb
Being locked out is not a problem
kaapstorm 6b79a5e
Drop `attempt_forward_now()`
kaapstorm 61a0a00
Drop `fire_synchronously` param
kaapstorm 04c8177
Drop `send_request()`
kaapstorm f586d2c
Drop `get_payload()`
kaapstorm eb1f424
fixup! Index filtered fields, add `max_workers`
kaapstorm File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
from django.apps import AppConfig | ||
|
||
|
||
class PGLockConfig(AppConfig): | ||
name = 'corehq.apps.pg_lock' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
# Generated by Django 4.2.14 on 2024-08-09 18:49 | ||
|
||
from django.db import migrations, models | ||
|
||
|
||
class Migration(migrations.Migration): | ||
|
||
initial = True | ||
|
||
dependencies = [] | ||
|
||
operations = [ | ||
migrations.CreateModel( | ||
name="PGLock", | ||
fields=[ | ||
( | ||
"key", | ||
models.CharField(max_length=255, primary_key=True, serialize=False), | ||
), | ||
("expires_at", models.DateTimeField(blank=True, null=True)), | ||
], | ||
), | ||
] |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
""" | ||
A partial implementation of a lock using PostgreSQL. It does not | ||
implement blocking. | ||
|
||
The intention of using Postgres for locking is to have a lock that can | ||
be used for coordinating across multiple worker processes. | ||
""" | ||
from contextlib import contextmanager | ||
from datetime import datetime, timedelta | ||
|
||
from django.db import models, IntegrityError | ||
|
||
|
||
class PGLock(models.Model): | ||
key = models.CharField(max_length=255, primary_key=True) | ||
expires_at = models.DateTimeField(null=True, blank=True) | ||
|
||
|
||
class Lock: | ||
def __init__(self, key): | ||
self.key = key | ||
|
||
def __str__(self): | ||
return self.key | ||
|
||
@property | ||
def name(self): # Used by MeteredLock | ||
return self.key | ||
|
||
def acquire(self, blocking=True, timeout=-1): | ||
if blocking: | ||
raise NotImplementedError("Blocking is not supported") | ||
|
||
if timeout >= 0: | ||
expires_at = datetime.utcnow() + timedelta(seconds=timeout) | ||
else: | ||
expires_at = None | ||
|
||
try: | ||
pg_lock, created = PGLock.objects.get_or_create( | ||
key=self.key, | ||
defaults={'expires_at': expires_at}, | ||
) | ||
if created: | ||
return True | ||
if ( | ||
pg_lock.expires_at is not None | ||
and pg_lock.expires_at <= datetime.utcnow() | ||
): | ||
# Lock has expired | ||
pg_lock.expires_at = expires_at | ||
pg_lock.save() | ||
return True | ||
return False | ||
except IntegrityError: | ||
return False | ||
|
||
def release(self): | ||
PGLock.objects.filter(key=self.key).delete() | ||
|
||
def locked(self): | ||
return ( | ||
PGLock.objects | ||
.filter(key=self.key) | ||
.filter( | ||
models.Q(expires_at__isnull=True) | ||
| models.Q(expires_at__gt=datetime.utcnow()) | ||
) | ||
.exists() | ||
) | ||
|
||
|
||
@contextmanager | ||
def lock(key, timeout=-1): | ||
lock = Lock(key) | ||
acquired = False | ||
try: | ||
acquired = lock.acquire(blocking=False, timeout=timeout) | ||
yield acquired | ||
finally: | ||
if acquired: | ||
lock.release() |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
from datetime import datetime | ||
from unittest import expectedFailure | ||
from unittest.mock import patch | ||
|
||
from django.test import TestCase | ||
|
||
from corehq.apps.pg_lock.models import Lock, lock | ||
from dimagi.utils.couch import get_redis_lock, get_pg_lock | ||
|
||
|
||
class PGLockTests(TestCase): | ||
|
||
def test_acquires_lock_when_not_locked(self): | ||
lock_instance = Lock('test_lock') | ||
acquired = lock_instance.acquire(blocking=False) | ||
self.assertTrue(acquired) | ||
self.assertTrue(lock_instance.locked()) | ||
lock_instance.release() | ||
|
||
def test_does_not_acquire_lock_when_already_locked(self): | ||
lock_instance = Lock('test_lock') | ||
lock_instance.acquire(blocking=False) | ||
another_lock_instance = Lock('test_lock') | ||
acquired = another_lock_instance.acquire(blocking=False) | ||
self.assertFalse(acquired) | ||
lock_instance.release() | ||
|
||
def test_releases_lock(self): | ||
lock_instance = Lock('test_lock') | ||
lock_instance.acquire(blocking=False) | ||
lock_instance.release() | ||
self.assertFalse(lock_instance.locked()) | ||
|
||
def test_releases_lock_not_acquired(self): | ||
lock_instance = Lock('test_lock') | ||
lock_instance.acquire(blocking=False) | ||
another_lock_instance = Lock('test_lock') | ||
another_lock_instance.release() | ||
self.assertFalse(lock_instance.locked()) | ||
|
||
@patch('corehq.apps.pg_lock.models.datetime') | ||
def test_acquires_lock_after_expiration(self, mock_datetime): | ||
lock_instance = Lock('test_lock') | ||
mock_datetime.utcnow.return_value = datetime(2023, 1, 1, 12, 0, 0) | ||
lock_instance.acquire(blocking=False, timeout=1) | ||
mock_datetime.utcnow.return_value = datetime(2023, 1, 1, 12, 0, 2) | ||
acquired = lock_instance.acquire(blocking=False) | ||
self.assertTrue(acquired) | ||
lock_instance.release() | ||
|
||
def test_context_manager_acquires_and_releases_lock(self): | ||
with lock('test_lock') as acquired: | ||
self.assertTrue(acquired) | ||
lock_instance = Lock('test_lock') | ||
self.assertTrue(lock_instance.locked()) | ||
lock_instance = Lock('test_lock') | ||
self.assertFalse(lock_instance.locked()) | ||
|
||
|
||
class TestLockWorkers(TestCase): | ||
|
||
@expectedFailure | ||
def test_release_redis_lock_not_acquired(self): | ||
# Worker 1: | ||
lock1 = get_redis_lock('test-key', timeout=1, name='test-name') | ||
self.assertTrue(lock1.acquire(blocking=False)) | ||
self.assertTrue(lock1.locked()) | ||
|
||
# Worker 2: | ||
lock2 = get_redis_lock('test-key', timeout=1, name='test-name') | ||
lock2.release() # redis.exceptions.LockError: Cannot release an unlocked lock | ||
|
||
self.assertFalse(lock1.locked()) | ||
|
||
def test_release_pg_lock_not_acquired(self): | ||
# Worker 1: | ||
lock1 = get_pg_lock('test-key', name='test-name') | ||
self.assertTrue(lock1.acquire(blocking=False)) | ||
self.assertTrue(lock1.locked()) | ||
|
||
# Worker 2: | ||
lock2 = get_pg_lock('test-key', name='test-name') | ||
lock2.release() | ||
|
||
self.assertFalse(lock1.locked()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -144,6 +144,7 @@ def options(self): | |
State.Pending, | ||
State.Cancelled, | ||
State.Fail, | ||
State.InvalidPayload, | ||
]] | ||
|
||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
46 changes: 46 additions & 0 deletions
46
...otech/repeaters/migrations/0013_repeater_max_workers_alter_repeater_is_paused_and_more.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
from django.db import migrations, models | ||
|
||
|
||
class Migration(migrations.Migration): | ||
|
||
dependencies = [ | ||
("repeaters", "0012_formexpressionrepeater_arcgisformexpressionrepeater"), | ||
] | ||
|
||
operations = [ | ||
migrations.AddField( | ||
model_name="repeater", | ||
name="max_workers", | ||
field=models.IntegerField(default=7), | ||
), | ||
migrations.AlterField( | ||
model_name="repeater", | ||
name="is_paused", | ||
field=models.BooleanField(db_index=True, default=False), | ||
), | ||
migrations.AlterField( | ||
model_name="repeater", | ||
name="next_attempt_at", | ||
field=models.DateTimeField(blank=True, db_index=True, null=True), | ||
), | ||
migrations.AlterField( | ||
model_name="repeatrecord", | ||
name="domain", | ||
field=models.CharField(db_index=True, max_length=126), | ||
), | ||
migrations.AlterField( | ||
model_name="repeatrecord", | ||
name="state", | ||
field=models.PositiveSmallIntegerField( | ||
choices=[ | ||
(1, "Pending"), | ||
(2, "Failed"), | ||
(4, "Succeeded"), | ||
(8, "Cancelled"), | ||
(16, "Empty"), | ||
], | ||
db_index=True, | ||
default=1, | ||
), | ||
), | ||
] |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What do you think of adding this status in a separate PR? Seems like we could do it before we change repeater processing logic, and it would simplify this PR, which is getting pretty large.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I like this idea!