django-webhook-outbox 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- django_webhook_outbox-1.0.0.dist-info/METADATA +195 -0
- django_webhook_outbox-1.0.0.dist-info/RECORD +33 -0
- django_webhook_outbox-1.0.0.dist-info/WHEEL +4 -0
- django_webhook_outbox-1.0.0.dist-info/licenses/LICENSE +21 -0
- webhook_outbox/__init__.py +11 -0
- webhook_outbox/admin.py +390 -0
- webhook_outbox/apps.py +12 -0
- webhook_outbox/checks.py +237 -0
- webhook_outbox/conf.py +110 -0
- webhook_outbox/contrib/__init__.py +0 -0
- webhook_outbox/contrib/celery/__init__.py +17 -0
- webhook_outbox/contrib/celery/apps.py +7 -0
- webhook_outbox/contrib/celery/schedule.py +42 -0
- webhook_outbox/contrib/celery/tasks.py +66 -0
- webhook_outbox/locale/ru/LC_MESSAGES/django.mo +0 -0
- webhook_outbox/locale/ru/LC_MESSAGES/django.po +188 -0
- webhook_outbox/management/__init__.py +0 -0
- webhook_outbox/management/commands/__init__.py +0 -0
- webhook_outbox/management/commands/webhook_outbox_deliver.py +42 -0
- webhook_outbox/management/commands/webhook_outbox_poll.py +11 -0
- webhook_outbox/management/commands/webhook_outbox_worker.py +58 -0
- webhook_outbox/migrations/0001_initial.py +239 -0
- webhook_outbox/migrations/__init__.py +0 -0
- webhook_outbox/models.py +230 -0
- webhook_outbox/py.typed +0 -0
- webhook_outbox/runner.py +147 -0
- webhook_outbox/services/__init__.py +11 -0
- webhook_outbox/services/channels/__init__.py +86 -0
- webhook_outbox/services/channels/base.py +95 -0
- webhook_outbox/services/channels/webhook.py +123 -0
- webhook_outbox/services/delivery.py +164 -0
- webhook_outbox/services/poller.py +255 -0
- webhook_outbox/services/template.py +196 -0
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: django-webhook-outbox
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Outgoing webhooks for Django models: timestamp polling, a transactional outbox and retrying delivery.
|
|
5
|
+
Project-URL: Homepage, https://github.com/omnichem/django-webhook-outbox
|
|
6
|
+
Project-URL: Documentation, https://github.com/omnichem/django-webhook-outbox/tree/master/docs
|
|
7
|
+
Project-URL: Changelog, https://github.com/omnichem/django-webhook-outbox/blob/master/CHANGELOG.md
|
|
8
|
+
Project-URL: Issues, https://github.com/omnichem/django-webhook-outbox/issues
|
|
9
|
+
Project-URL: Source, https://github.com/omnichem/django-webhook-outbox
|
|
10
|
+
Author: OmniChem
|
|
11
|
+
License-Expression: MIT
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: django,notifications,outbox,polling,webhook,webhooks
|
|
14
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
15
|
+
Classifier: Environment :: Web Environment
|
|
16
|
+
Classifier: Framework :: Django
|
|
17
|
+
Classifier: Framework :: Django :: 4.2
|
|
18
|
+
Classifier: Framework :: Django :: 5.0
|
|
19
|
+
Classifier: Framework :: Django :: 5.1
|
|
20
|
+
Classifier: Framework :: Django :: 5.2
|
|
21
|
+
Classifier: Intended Audience :: Developers
|
|
22
|
+
Classifier: Natural Language :: English
|
|
23
|
+
Classifier: Natural Language :: Russian
|
|
24
|
+
Classifier: Operating System :: OS Independent
|
|
25
|
+
Classifier: Programming Language :: Python
|
|
26
|
+
Classifier: Programming Language :: Python :: 3
|
|
27
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
28
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
29
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
30
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
31
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
32
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
33
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
34
|
+
Classifier: Typing :: Typed
|
|
35
|
+
Requires-Python: >=3.10
|
|
36
|
+
Requires-Dist: django<6,>=4.2
|
|
37
|
+
Requires-Dist: httpx>=0.27
|
|
38
|
+
Provides-Extra: celery
|
|
39
|
+
Requires-Dist: celery>=5.3; extra == 'celery'
|
|
40
|
+
Description-Content-Type: text/markdown
|
|
41
|
+
|
|
42
|
+
# django-webhook-outbox
|
|
43
|
+
|
|
44
|
+
Outgoing webhooks for Django models, configured in the Django admin.
|
|
45
|
+
|
|
46
|
+
You pick a model and an event (`insert` or `update`) in the admin and write
|
|
47
|
+
a message template. A poller finds new and changed rows by their
|
|
48
|
+
`created_at` / `updated_at` timestamps and writes them to an outbox table.
|
|
49
|
+
A delivery pass then POSTs each outbox entry as JSON to the channel's URL and
|
|
50
|
+
retries failures.
|
|
51
|
+
|
|
52
|
+
- No database triggers and no signals: any model with `created_at` /
|
|
53
|
+
`updated_at` fields can be tracked, including models of third-party apps.
|
|
54
|
+
- Delivery goes through an outbox table: pending, sent and failed entries are
|
|
55
|
+
visible in the admin, and failed ones can be retried from there.
|
|
56
|
+
- Celery is optional. The core runs from a management command
|
|
57
|
+
(`webhook_outbox_worker`), cron, or any scheduler; `webhook_outbox.contrib.celery`
|
|
58
|
+
provides ready-made tasks if you already use Celery.
|
|
59
|
+
- English and Russian admin.
|
|
60
|
+
|
|
61
|
+
The package was extracted from a production Django service. Release 1.0.0
|
|
62
|
+
keeps that code's behaviour exactly, known limitations included. They are
|
|
63
|
+
listed in [docs/semantics.md](docs/semantics.md); read that page before you
|
|
64
|
+
rely on the package for anything that must not lose or duplicate events.
|
|
65
|
+
|
|
66
|
+
## Requirements
|
|
67
|
+
|
|
68
|
+
- Python 3.10+
|
|
69
|
+
- Django 4.2, 5.0, 5.1 or 5.2 (CI runs 4.2, 5.0 and 5.2 on PostgreSQL)
|
|
70
|
+
- httpx 0.27+
|
|
71
|
+
- Celery 5.3+ (optional, `[celery]` extra)
|
|
72
|
+
|
|
73
|
+
## Installation
|
|
74
|
+
|
|
75
|
+
```console
|
|
76
|
+
pip install django-webhook-outbox
|
|
77
|
+
# or, with the Celery tasks:
|
|
78
|
+
pip install "django-webhook-outbox[celery]"
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
# settings.py
|
|
83
|
+
INSTALLED_APPS = [
|
|
84
|
+
# ...
|
|
85
|
+
"django.contrib.admin",
|
|
86
|
+
"django.contrib.contenttypes",
|
|
87
|
+
"webhook_outbox",
|
|
88
|
+
]
|
|
89
|
+
|
|
90
|
+
WEBHOOK_OUTBOX = {
|
|
91
|
+
"SITE_URL": "https://shop.example.com", # used by {admin_link}
|
|
92
|
+
}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
```console
|
|
96
|
+
python manage.py migrate webhook_outbox
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## Quick start
|
|
100
|
+
|
|
101
|
+
1. Make sure the model you want to track has `created_at` (insert events)
|
|
102
|
+
and `updated_at` (update events) fields. The easiest way is to inherit the
|
|
103
|
+
bundled base class:
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
from webhook_outbox.models import TimeStampedModel
|
|
107
|
+
|
|
108
|
+
class Order(TimeStampedModel):
|
|
109
|
+
number = models.CharField(max_length=20)
|
|
110
|
+
customer = models.ForeignKey(Customer, on_delete=models.PROTECT)
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
2. In the admin, add a **Notification Channel**, type *Webhook*, with this
|
|
114
|
+
config:
|
|
115
|
+
|
|
116
|
+
```json
|
|
117
|
+
{"url": "https://receiver.example.com/hooks/orders",
|
|
118
|
+
"headers": {"Authorization": "Bearer <token>"},
|
|
119
|
+
"timeout": 10}
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
3. Add a **Tracked Table**: model *orders*, event *Insert*, the channel from
|
|
123
|
+
step 2, and a message template:
|
|
124
|
+
|
|
125
|
+
```text
|
|
126
|
+
New order {number} from {customer.name}
|
|
127
|
+
{admin_link}
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
4. Run a worker (see below). The first poll of a tracked table only stores
|
|
131
|
+
its starting point and does not backfill. Orders created after that are
|
|
132
|
+
POSTed to the receiver:
|
|
133
|
+
|
|
134
|
+
```json
|
|
135
|
+
{
|
|
136
|
+
"event": "insert",
|
|
137
|
+
"source_model": "shop.order",
|
|
138
|
+
"source_pk": "1042",
|
|
139
|
+
"tracked_table": "New orders",
|
|
140
|
+
"message": "New order A-1042 from Acme Corp\nhttps://shop.example.com/admin/shop/order/1042/change/",
|
|
141
|
+
"occurred_at": "2026-08-03T10:00:00.123456+00:00"
|
|
142
|
+
}
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
A 2xx response marks the entry *sent*. Any other response, a timeout or
|
|
146
|
+
a connection error counts as a failed attempt. After `MAX_RETRIES` (3)
|
|
147
|
+
failed attempts the entry becomes *failed*.
|
|
148
|
+
|
|
149
|
+
### Running without Celery
|
|
150
|
+
|
|
151
|
+
```console
|
|
152
|
+
python manage.py webhook_outbox_worker # poll every 30s, deliver every 10s
|
|
153
|
+
python manage.py webhook_outbox_worker --once # one pass, e.g. from cron
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
Run **one** worker process per database (see
|
|
157
|
+
[limitations](docs/semantics.md#known-limitations)). It stops cleanly on
|
|
158
|
+
SIGTERM/SIGINT. Systemd, Kubernetes and cron examples are in
|
|
159
|
+
[docs/runners.md](docs/runners.md).
|
|
160
|
+
|
|
161
|
+
### Running with Celery
|
|
162
|
+
|
|
163
|
+
```python
|
|
164
|
+
# settings.py
|
|
165
|
+
from webhook_outbox.contrib.celery.schedule import beat_schedule
|
|
166
|
+
|
|
167
|
+
INSTALLED_APPS += ["webhook_outbox.contrib.celery"]
|
|
168
|
+
|
|
169
|
+
CELERY_BEAT_SCHEDULE = {
|
|
170
|
+
**beat_schedule(), # poll every 30s, deliver every 10s
|
|
171
|
+
# ... your other entries
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
WEBHOOK_OUTBOX = {
|
|
175
|
+
# "Retry" in the admin pushes the entry to Celery immediately
|
|
176
|
+
"ADMIN_RETRY_HOOK": "webhook_outbox.contrib.celery.tasks.enqueue_single_notification",
|
|
177
|
+
}
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
## Documentation
|
|
181
|
+
|
|
182
|
+
- [Concepts](docs/concepts.md): channels, tracked tables, the outbox, the data flow
|
|
183
|
+
- [Semantics and known limitations](docs/semantics.md)
|
|
184
|
+
- [Settings reference](docs/settings.md)
|
|
185
|
+
- [Envelope v1](docs/envelope.md): the JSON document receivers get
|
|
186
|
+
- [Channels](docs/channels.md): webhook config, writing your own channel
|
|
187
|
+
- [Security notes](docs/security.md)
|
|
188
|
+
- [Runners](docs/runners.md): worker loop, cron, Celery
|
|
189
|
+
- [Adopting the app in a service without Celery](docs/without-celery.md)
|
|
190
|
+
- [Upgrade notes](docs/upgrading.md), including migrating from the original in-house app
|
|
191
|
+
- [Changelog](CHANGELOG.md), [Contributing](CONTRIBUTING.md)
|
|
192
|
+
|
|
193
|
+
## License
|
|
194
|
+
|
|
195
|
+
MIT, see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
webhook_outbox/__init__.py,sha256=_wsI2yI5nmEDLKIqvIFV5aMi00qlxI2rbSbehd_5JyI,361
|
|
2
|
+
webhook_outbox/admin.py,sha256=jmWcgWHnoRvY0fz3MBE4dLXV9iUmVeQ4QAIgmrkE_vM,12749
|
|
3
|
+
webhook_outbox/apps.py,sha256=vfnH_ERbfOqV2oe3VYI5lU8JTW59l0RzaL9G7kq9z_8,378
|
|
4
|
+
webhook_outbox/checks.py,sha256=mInO8DLlBg1RUV0tpQvGbRCv5WkWT4swXweY8tCUEXA,8558
|
|
5
|
+
webhook_outbox/conf.py,sha256=CtZd-WR5GkXStHH-cgQxv1mYCxzAv0C-Ix8sbNm0YVg,3485
|
|
6
|
+
webhook_outbox/models.py,sha256=OkxxrtVmhbcVCnWhiT8LxGvRXialV5DvGHw6Ghf91X4,6414
|
|
7
|
+
webhook_outbox/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
webhook_outbox/runner.py,sha256=So-3xQPrshafK8dTHb7JvNQZ3ZAslzoQ7ezq50Qw9xg,5253
|
|
9
|
+
webhook_outbox/contrib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
10
|
+
webhook_outbox/contrib/celery/__init__.py,sha256=g3VWWA7lxkoHb2JcOKN85WkO-qBtBS9lhuFLxStlNJw,617
|
|
11
|
+
webhook_outbox/contrib/celery/apps.py,sha256=smiGmUDFjj8rUJZq3eMrv5Wj9LfexVpKXC93UG612a0,204
|
|
12
|
+
webhook_outbox/contrib/celery/schedule.py,sha256=XFquNmB9pyj3BtAntBAJAAKKwBCEzEmmnlJrOASxyWo,1257
|
|
13
|
+
webhook_outbox/contrib/celery/tasks.py,sha256=zGB7wPY-Tdyupfm-8wPwv03t2Wc8C0f7u7W1rIMy3tw,1972
|
|
14
|
+
webhook_outbox/locale/ru/LC_MESSAGES/django.mo,sha256=zQIGwXYot4psPwsJJ0lD_LJxC0m8z_LofTmfvVlDul0,5568
|
|
15
|
+
webhook_outbox/locale/ru/LC_MESSAGES/django.po,sha256=vZOxqtU2eni1h95lY0AFZPknsrJKAOOeBqObuS6e-NM,5851
|
|
16
|
+
webhook_outbox/management/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
17
|
+
webhook_outbox/management/commands/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
18
|
+
webhook_outbox/management/commands/webhook_outbox_deliver.py,sha256=aSDT1XvVJTwgJUllRYLQpUASiJrBqhSdKtUyWZY0h_o,1613
|
|
19
|
+
webhook_outbox/management/commands/webhook_outbox_poll.py,sha256=qesUeSL5omRIA8QlaFdbRLTDSMOhjPZEWBFIUzZcKD4,332
|
|
20
|
+
webhook_outbox/management/commands/webhook_outbox_worker.py,sha256=kB2y6aT2fvPXDBWy0uJiJJb1GaMcqtbWr3qaZglB658,1893
|
|
21
|
+
webhook_outbox/migrations/0001_initial.py,sha256=28hRs4xQLddlBgxXxunQCESiLCOCZI8rwN5yUAE_UOg,8829
|
|
22
|
+
webhook_outbox/migrations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
23
|
+
webhook_outbox/services/__init__.py,sha256=d1uhiloBMqKdkKtmbxTaQA1YYIWSJiPlsHEs1qbygu0,297
|
|
24
|
+
webhook_outbox/services/delivery.py,sha256=ItLQyHWWGRrNyYZ_BIsoy4hY73LBqMIIkQqLYCGCB0k,5354
|
|
25
|
+
webhook_outbox/services/poller.py,sha256=Mb3aIslpbjqd5GBNcrkMj5vYgRcsAtQh2OsIUj7RWKE,8220
|
|
26
|
+
webhook_outbox/services/template.py,sha256=-_kQDdQCzpIz27C-1vc5vkFOBFh4_RjaNaFj1LDXPyw,5671
|
|
27
|
+
webhook_outbox/services/channels/__init__.py,sha256=148TdJ2kgKe7n-hYE1juBNSnpM69m5hQCzNQxC5fZ1k,2638
|
|
28
|
+
webhook_outbox/services/channels/base.py,sha256=CvsBPc4yf0j6eKriKSVQz2F8p_gpGCjtf0XlQBa7as8,2793
|
|
29
|
+
webhook_outbox/services/channels/webhook.py,sha256=wec6k6n2kCwwgAwcyRUPsP4dIVDtxa_lP4mDsiKyDYc,4675
|
|
30
|
+
django_webhook_outbox-1.0.0.dist-info/METADATA,sha256=vinTPm_xB5_M6PXXwfLFHX6fIxE5WCTgNF0mevl-sQA,6797
|
|
31
|
+
django_webhook_outbox-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
32
|
+
django_webhook_outbox-1.0.0.dist-info/licenses/LICENSE,sha256=jYvrrET9huz7whM_AV9Aoujq7bdLIXKaNL4wsHRgXT4,1065
|
|
33
|
+
django_webhook_outbox-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 omnichem
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""django-webhook-outbox: outgoing webhooks for Django models."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError
|
|
4
|
+
from importlib.metadata import version as _version
|
|
5
|
+
|
|
6
|
+
try:
|
|
7
|
+
__version__ = _version("django-webhook-outbox")
|
|
8
|
+
except PackageNotFoundError: # pragma: no cover - running from a bare checkout
|
|
9
|
+
__version__ = "0.0.0"
|
|
10
|
+
|
|
11
|
+
__all__ = ["__version__"]
|
webhook_outbox/admin.py
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
|
|
3
|
+
from django import forms
|
|
4
|
+
from django.apps import apps
|
|
5
|
+
from django.contrib import admin, messages
|
|
6
|
+
from django.contrib.contenttypes.models import ContentType
|
|
7
|
+
from django.db.models import QuerySet
|
|
8
|
+
from django.http import HttpRequest
|
|
9
|
+
from django.utils import timezone
|
|
10
|
+
from django.utils.html import format_html
|
|
11
|
+
from django.utils.module_loading import import_string
|
|
12
|
+
from django.utils.translation import gettext_lazy as _
|
|
13
|
+
|
|
14
|
+
from .conf import get_setting
|
|
15
|
+
from .models import NotificationChannel, NotificationOutbox, TrackedTable
|
|
16
|
+
from .services.channels import get_channel_registry
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
SELF_APP_NAME = "webhook_outbox"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _is_excluded_app(app_config) -> bool:
|
|
24
|
+
name = app_config.name
|
|
25
|
+
if name.startswith("django."):
|
|
26
|
+
return True
|
|
27
|
+
# Self-tracking guard: the package's own models (and its contrib apps)
|
|
28
|
+
# would feed the outbox with its own rows.
|
|
29
|
+
if name == SELF_APP_NAME or name.startswith(f"{SELF_APP_NAME}."):
|
|
30
|
+
return True
|
|
31
|
+
excluded = set(get_setting("TRACKABLE_EXCLUDE_APPS") or ())
|
|
32
|
+
return app_config.label in excluded or name in excluded
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def get_trackable_content_types():
|
|
36
|
+
"""
|
|
37
|
+
Get ContentType objects for models that have timestamp fields.
|
|
38
|
+
Returns list of (content_type_id, verbose_name) tuples.
|
|
39
|
+
|
|
40
|
+
Skips django.* apps, webhook_outbox itself and TRACKABLE_EXCLUDE_APPS.
|
|
41
|
+
"""
|
|
42
|
+
choices = []
|
|
43
|
+
for app_config in apps.get_app_configs():
|
|
44
|
+
if _is_excluded_app(app_config):
|
|
45
|
+
continue
|
|
46
|
+
for model in app_config.get_models():
|
|
47
|
+
meta = model._meta
|
|
48
|
+
field_names = {f.name for f in meta.get_fields()}
|
|
49
|
+
if "created_at" in field_names:
|
|
50
|
+
has_updated = "updated_at" in field_names
|
|
51
|
+
suffix = "" if has_updated else " (INSERT only)"
|
|
52
|
+
ct = ContentType.objects.get_for_model(model)
|
|
53
|
+
label = f"{meta.verbose_name_plural}{suffix}"
|
|
54
|
+
choices.append((ct.pk, label))
|
|
55
|
+
return sorted(choices, key=lambda x: x[1])
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class TrackedTableForm(forms.ModelForm):
|
|
59
|
+
"""Custom form for TrackedTable with filtered content_type choices."""
|
|
60
|
+
|
|
61
|
+
class Meta:
|
|
62
|
+
model = TrackedTable
|
|
63
|
+
fields = "__all__" # noqa: DJ007 - the ModelAdmin fieldsets pick the fields
|
|
64
|
+
|
|
65
|
+
def __init__(self, *args, **kwargs):
|
|
66
|
+
super().__init__(*args, **kwargs)
|
|
67
|
+
if "content_type" in self.fields:
|
|
68
|
+
choices = get_trackable_content_types()
|
|
69
|
+
field = self.fields["content_type"]
|
|
70
|
+
# Restrict the queryset too: choices alone only change the widget,
|
|
71
|
+
# a posted id outside them would still validate.
|
|
72
|
+
field.queryset = ContentType.objects.filter(
|
|
73
|
+
pk__in=[pk for pk, _label in choices]
|
|
74
|
+
)
|
|
75
|
+
field.choices = [("", "---------")] + choices
|
|
76
|
+
field.widget = forms.Select(choices=[("", "---------")] + choices)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def get_channel_type_choices():
|
|
80
|
+
labels = dict(NotificationChannel.ChannelType.choices)
|
|
81
|
+
choices = []
|
|
82
|
+
for channel_type, channel_class in get_channel_registry().items():
|
|
83
|
+
label = labels.get(channel_type) or getattr(
|
|
84
|
+
channel_class, "verbose_name", channel_type
|
|
85
|
+
)
|
|
86
|
+
choices.append((channel_type, label))
|
|
87
|
+
return choices
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class NotificationChannelForm(forms.ModelForm):
|
|
91
|
+
"""Channel types offered from the channel registry (WEBHOOK_OUTBOX['CHANNELS'])."""
|
|
92
|
+
|
|
93
|
+
class Meta:
|
|
94
|
+
model = NotificationChannel
|
|
95
|
+
fields = "__all__" # noqa: DJ007 - the ModelAdmin fieldsets pick the fields
|
|
96
|
+
|
|
97
|
+
def __init__(self, *args, **kwargs):
|
|
98
|
+
super().__init__(*args, **kwargs)
|
|
99
|
+
if "channel_type" in self.fields:
|
|
100
|
+
field = self.fields["channel_type"]
|
|
101
|
+
self.fields["channel_type"] = forms.ChoiceField(
|
|
102
|
+
choices=get_channel_type_choices(),
|
|
103
|
+
initial=field.initial,
|
|
104
|
+
label=field.label,
|
|
105
|
+
help_text=field.help_text,
|
|
106
|
+
required=True,
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
def _get_validation_exclusions(self):
|
|
110
|
+
# The model field's choices only list the built-in "webhook" type (so
|
|
111
|
+
# migrations do not depend on settings); the form field above already
|
|
112
|
+
# validated the value against the registry.
|
|
113
|
+
exclude = super()._get_validation_exclusions()
|
|
114
|
+
exclude.add("channel_type")
|
|
115
|
+
return exclude
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@admin.register(NotificationChannel)
|
|
119
|
+
class NotificationChannelAdmin(admin.ModelAdmin):
|
|
120
|
+
form = NotificationChannelForm
|
|
121
|
+
list_display = [
|
|
122
|
+
"name",
|
|
123
|
+
"channel_type",
|
|
124
|
+
"is_active_colored",
|
|
125
|
+
"tracked_tables_count",
|
|
126
|
+
"created_at",
|
|
127
|
+
]
|
|
128
|
+
list_filter = ["channel_type", "is_active"]
|
|
129
|
+
search_fields = ["name"]
|
|
130
|
+
readonly_fields = ["created_at", "updated_at"]
|
|
131
|
+
ordering = ["name"]
|
|
132
|
+
|
|
133
|
+
fieldsets = (
|
|
134
|
+
(
|
|
135
|
+
None,
|
|
136
|
+
{
|
|
137
|
+
"fields": ("name", "channel_type", "is_active"),
|
|
138
|
+
},
|
|
139
|
+
),
|
|
140
|
+
(
|
|
141
|
+
_("Configuration"),
|
|
142
|
+
{
|
|
143
|
+
"fields": ("config",),
|
|
144
|
+
"description": _(
|
|
145
|
+
'Webhook: {"url": "https://example.com/hooks/outbox", '
|
|
146
|
+
'"headers": {"Authorization": "Bearer ..."}, "timeout": 30}. '
|
|
147
|
+
"Only url is required; headers authenticate the outgoing call."
|
|
148
|
+
),
|
|
149
|
+
},
|
|
150
|
+
),
|
|
151
|
+
(
|
|
152
|
+
_("Timestamps"),
|
|
153
|
+
{
|
|
154
|
+
"fields": ("created_at", "updated_at"),
|
|
155
|
+
"classes": ("collapse",),
|
|
156
|
+
},
|
|
157
|
+
),
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
@admin.display(description=_("Active"), boolean=True)
|
|
161
|
+
def is_active_colored(self, obj: NotificationChannel) -> bool:
|
|
162
|
+
return obj.is_active
|
|
163
|
+
|
|
164
|
+
@admin.display(description=_("Tracked Tables"))
|
|
165
|
+
def tracked_tables_count(self, obj: NotificationChannel) -> int:
|
|
166
|
+
return obj.tracked_tables.count()
|
|
167
|
+
|
|
168
|
+
def get_queryset(self, request: HttpRequest) -> QuerySet:
|
|
169
|
+
return super().get_queryset(request).prefetch_related("tracked_tables")
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
@admin.register(TrackedTable)
|
|
173
|
+
class TrackedTableAdmin(admin.ModelAdmin):
|
|
174
|
+
form = TrackedTableForm
|
|
175
|
+
list_display = [
|
|
176
|
+
"name",
|
|
177
|
+
"model_display",
|
|
178
|
+
"event_type",
|
|
179
|
+
"channel",
|
|
180
|
+
"is_active_colored",
|
|
181
|
+
"last_polled_at",
|
|
182
|
+
]
|
|
183
|
+
list_filter = ["event_type", "is_active", "channel"]
|
|
184
|
+
search_fields = ["name"]
|
|
185
|
+
readonly_fields = [
|
|
186
|
+
"created_at",
|
|
187
|
+
"updated_at",
|
|
188
|
+
"last_polled_at",
|
|
189
|
+
]
|
|
190
|
+
ordering = ["name"]
|
|
191
|
+
autocomplete_fields = ["channel"]
|
|
192
|
+
|
|
193
|
+
fieldsets = (
|
|
194
|
+
(
|
|
195
|
+
None,
|
|
196
|
+
{
|
|
197
|
+
"fields": ("name", "is_active"),
|
|
198
|
+
},
|
|
199
|
+
),
|
|
200
|
+
(
|
|
201
|
+
_("Model Configuration"),
|
|
202
|
+
{
|
|
203
|
+
"fields": ("content_type", "event_type"),
|
|
204
|
+
"description": _(
|
|
205
|
+
"Select the model to track and the event type. "
|
|
206
|
+
"INSERT: notifies on new records. "
|
|
207
|
+
"UPDATE: notifies on any change to existing records."
|
|
208
|
+
),
|
|
209
|
+
},
|
|
210
|
+
),
|
|
211
|
+
(
|
|
212
|
+
_("Notification"),
|
|
213
|
+
{
|
|
214
|
+
"fields": ("message_template", "channel"),
|
|
215
|
+
"description": _(
|
|
216
|
+
"Use {field_name} for direct fields, "
|
|
217
|
+
"{relation.field} for FK traversal, "
|
|
218
|
+
"{admin_link} for admin panel URL. "
|
|
219
|
+
"Example: 'New request for {company.company_name}\\n{admin_link}'"
|
|
220
|
+
),
|
|
221
|
+
},
|
|
222
|
+
),
|
|
223
|
+
(
|
|
224
|
+
_("Status"),
|
|
225
|
+
{
|
|
226
|
+
"fields": ("last_polled_at",),
|
|
227
|
+
"classes": ("collapse",),
|
|
228
|
+
},
|
|
229
|
+
),
|
|
230
|
+
(
|
|
231
|
+
_("Timestamps"),
|
|
232
|
+
{
|
|
233
|
+
"fields": ("created_at", "updated_at"),
|
|
234
|
+
"classes": ("collapse",),
|
|
235
|
+
},
|
|
236
|
+
),
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
@admin.display(description=_("Active"), boolean=True)
|
|
240
|
+
def is_active_colored(self, obj: TrackedTable) -> bool:
|
|
241
|
+
return obj.is_active
|
|
242
|
+
|
|
243
|
+
@admin.display(description=_("Model"))
|
|
244
|
+
def model_display(self, obj: TrackedTable) -> str:
|
|
245
|
+
if obj.content_type:
|
|
246
|
+
model_class = obj.content_type.model_class()
|
|
247
|
+
if model_class:
|
|
248
|
+
return model_class._meta.verbose_name_plural
|
|
249
|
+
return "-"
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _get_retry_hook():
|
|
253
|
+
hook = get_setting("ADMIN_RETRY_HOOK")
|
|
254
|
+
if hook is None:
|
|
255
|
+
return None
|
|
256
|
+
return import_string(hook) if isinstance(hook, str) else hook
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
@admin.register(NotificationOutbox)
|
|
260
|
+
class NotificationOutboxAdmin(admin.ModelAdmin):
|
|
261
|
+
list_display = [
|
|
262
|
+
"id",
|
|
263
|
+
"source_model",
|
|
264
|
+
"source_pk",
|
|
265
|
+
"event_type",
|
|
266
|
+
"status_colored",
|
|
267
|
+
"retry_count",
|
|
268
|
+
"created_at",
|
|
269
|
+
"sent_at",
|
|
270
|
+
]
|
|
271
|
+
list_filter = ["status", "event_type", "tracked_table", "tracked_table__channel"]
|
|
272
|
+
search_fields = ["source_model", "source_pk", "message"]
|
|
273
|
+
readonly_fields = [
|
|
274
|
+
"created_at",
|
|
275
|
+
"updated_at",
|
|
276
|
+
"tracked_table",
|
|
277
|
+
"source_model",
|
|
278
|
+
"source_pk",
|
|
279
|
+
"event_type",
|
|
280
|
+
"message",
|
|
281
|
+
"sent_at",
|
|
282
|
+
"retry_count",
|
|
283
|
+
]
|
|
284
|
+
ordering = ["-created_at"]
|
|
285
|
+
actions = ["retry_failed", "mark_as_sent"]
|
|
286
|
+
date_hierarchy = "created_at"
|
|
287
|
+
|
|
288
|
+
fieldsets = (
|
|
289
|
+
(
|
|
290
|
+
_("Source"),
|
|
291
|
+
{
|
|
292
|
+
"fields": ("tracked_table", "source_model", "source_pk", "event_type"),
|
|
293
|
+
},
|
|
294
|
+
),
|
|
295
|
+
(
|
|
296
|
+
_("Message"),
|
|
297
|
+
{
|
|
298
|
+
"fields": ("message",),
|
|
299
|
+
},
|
|
300
|
+
),
|
|
301
|
+
(
|
|
302
|
+
_("Status"),
|
|
303
|
+
{
|
|
304
|
+
"fields": ("status", "error_message", "retry_count", "sent_at"),
|
|
305
|
+
},
|
|
306
|
+
),
|
|
307
|
+
(
|
|
308
|
+
_("Timestamps"),
|
|
309
|
+
{
|
|
310
|
+
"fields": ("created_at", "updated_at"),
|
|
311
|
+
"classes": ("collapse",),
|
|
312
|
+
},
|
|
313
|
+
),
|
|
314
|
+
)
|
|
315
|
+
|
|
316
|
+
@admin.display(description=_("Status"))
|
|
317
|
+
def status_colored(self, obj: NotificationOutbox) -> str:
|
|
318
|
+
colors = {
|
|
319
|
+
NotificationOutbox.Status.PENDING: "#f0ad4e",
|
|
320
|
+
NotificationOutbox.Status.SENT: "#5cb85c",
|
|
321
|
+
NotificationOutbox.Status.FAILED: "#d9534f",
|
|
322
|
+
}
|
|
323
|
+
color = colors.get(obj.status, "#777")
|
|
324
|
+
return format_html(
|
|
325
|
+
'<span style="color: {}; font-weight: bold;">{}</span>',
|
|
326
|
+
color,
|
|
327
|
+
obj.get_status_display(),
|
|
328
|
+
)
|
|
329
|
+
|
|
330
|
+
@admin.action(description=_("Retry selected failed notifications"))
|
|
331
|
+
def retry_failed(self, request: HttpRequest, queryset: QuerySet) -> None:
|
|
332
|
+
"""
|
|
333
|
+
Reset FAILED entries to PENDING (retry_count 0, error cleared). The
|
|
334
|
+
next delivery pass sends them; ADMIN_RETRY_HOOK, if set, is called
|
|
335
|
+
with each entry's pk to push it right away.
|
|
336
|
+
"""
|
|
337
|
+
failed = queryset.filter(status=NotificationOutbox.Status.FAILED)
|
|
338
|
+
hook = _get_retry_hook()
|
|
339
|
+
count = 0
|
|
340
|
+
hook_errors = 0
|
|
341
|
+
|
|
342
|
+
for entry in failed:
|
|
343
|
+
entry.status = NotificationOutbox.Status.PENDING
|
|
344
|
+
entry.retry_count = 0
|
|
345
|
+
entry.error_message = ""
|
|
346
|
+
entry.save()
|
|
347
|
+
if hook is not None:
|
|
348
|
+
try:
|
|
349
|
+
hook(entry.pk)
|
|
350
|
+
except Exception:
|
|
351
|
+
# The entry is already PENDING: the worker picks it up.
|
|
352
|
+
logger.exception(f"ADMIN_RETRY_HOOK failed for entry #{entry.pk}")
|
|
353
|
+
hook_errors += 1
|
|
354
|
+
count += 1
|
|
355
|
+
|
|
356
|
+
self.message_user(
|
|
357
|
+
request,
|
|
358
|
+
_("Queued {} notification(s) for retry.").format(count),
|
|
359
|
+
messages.SUCCESS,
|
|
360
|
+
)
|
|
361
|
+
if hook_errors:
|
|
362
|
+
self.message_user(
|
|
363
|
+
request,
|
|
364
|
+
_(
|
|
365
|
+
"Immediate delivery could not be started for {} notification(s); "
|
|
366
|
+
"they will be sent by the next delivery run."
|
|
367
|
+
).format(hook_errors),
|
|
368
|
+
messages.WARNING,
|
|
369
|
+
)
|
|
370
|
+
|
|
371
|
+
@admin.action(description=_("Mark selected as sent (skip sending)"))
|
|
372
|
+
def mark_as_sent(self, request: HttpRequest, queryset: QuerySet) -> None:
|
|
373
|
+
updated = queryset.exclude(status=NotificationOutbox.Status.SENT).update(
|
|
374
|
+
status=NotificationOutbox.Status.SENT,
|
|
375
|
+
sent_at=timezone.now(),
|
|
376
|
+
)
|
|
377
|
+
|
|
378
|
+
self.message_user(
|
|
379
|
+
request,
|
|
380
|
+
_("Marked {} notification(s) as sent.").format(updated),
|
|
381
|
+
messages.SUCCESS,
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
def has_add_permission(self, request: HttpRequest) -> bool:
|
|
385
|
+
return False
|
|
386
|
+
|
|
387
|
+
def has_change_permission(self, request: HttpRequest, obj=None) -> bool:
|
|
388
|
+
if obj and obj.status == NotificationOutbox.Status.SENT:
|
|
389
|
+
return False
|
|
390
|
+
return super().has_change_permission(request, obj)
|
webhook_outbox/apps.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from django.apps import AppConfig
|
|
2
|
+
from django.utils.translation import gettext_lazy as _
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class WebhookOutboxConfig(AppConfig):
|
|
6
|
+
default_auto_field = "django.db.models.BigAutoField"
|
|
7
|
+
name = "webhook_outbox"
|
|
8
|
+
label = "webhook_outbox"
|
|
9
|
+
verbose_name = _("Webhook outbox")
|
|
10
|
+
|
|
11
|
+
def ready(self):
|
|
12
|
+
from . import checks # noqa: F401 (registers the system checks)
|