accordsync-django 0.3.0__tar.gz
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.
- accordsync_django-0.3.0/.gitignore +9 -0
- accordsync_django-0.3.0/LICENSE +202 -0
- accordsync_django-0.3.0/PKG-INFO +72 -0
- accordsync_django-0.3.0/README.md +58 -0
- accordsync_django-0.3.0/pyproject.toml +24 -0
- accordsync_django-0.3.0/src/accordsync_django/__init__.py +5 -0
- accordsync_django-0.3.0/src/accordsync_django/apps.py +10 -0
- accordsync_django-0.3.0/src/accordsync_django/checks.py +24 -0
- accordsync_django-0.3.0/src/accordsync_django/conf.py +106 -0
- accordsync_django-0.3.0/src/accordsync_django/management/__init__.py +0 -0
- accordsync_django-0.3.0/src/accordsync_django/management/commands/__init__.py +0 -0
- accordsync_django-0.3.0/src/accordsync_django/management/commands/accord_compact.py +16 -0
- accordsync_django-0.3.0/src/accordsync_django/management/commands/accord_migrate.py +16 -0
- accordsync_django-0.3.0/src/accordsync_django/py.typed +0 -0
- accordsync_django-0.3.0/src/accordsync_django/urls.py +12 -0
- accordsync_django-0.3.0/src/accordsync_django/views.py +48 -0
- accordsync_django-0.3.0/tests/accordsync_django_testdef.py +11 -0
- accordsync_django-0.3.0/tests/conftest.py +18 -0
- accordsync_django-0.3.0/tests/test_django.py +130 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: accordsync-django
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Accord sync server for Django: app, URLs and management commands.
|
|
5
|
+
Project-URL: Homepage, https://accord.benhattab.pro
|
|
6
|
+
Project-URL: Source, https://github.com/crossben/accordsync-python
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: crdt,local-first,offline-first,sync
|
|
10
|
+
Requires-Python: >=3.11
|
|
11
|
+
Requires-Dist: accordsync-server<0.4,>=0.3
|
|
12
|
+
Requires-Dist: django>=5.1
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
|
|
15
|
+
# accordsync-django
|
|
16
|
+
|
|
17
|
+
The Accord sync server for Django: an app with the `/v1/push`, `/v1/pull` and `/health` URLs,
|
|
18
|
+
management commands `accord_migrate` and `accord_compact`, and a system check. All behaviour
|
|
19
|
+
comes from `accordsync-server`; this package only routes to it. Part of
|
|
20
|
+
[Accord](https://accord.benhattab.pro).
|
|
21
|
+
|
|
22
|
+
## Install
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
pip install accordsync-django
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Configure
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
# settings.py
|
|
32
|
+
INSTALLED_APPS = [..., "accordsync_django"]
|
|
33
|
+
ACCORD_SERVER = "myapp.sync:server" # a ServerDefinition made with define_server(...)
|
|
34
|
+
ACCORD_DATABASE_URL = "postgresql://..." # optional, see below
|
|
35
|
+
ACCORD_POOL_SIZE = 20 # optional
|
|
36
|
+
ACCORD_SCHEDULE_COMPACTION = True # optional
|
|
37
|
+
|
|
38
|
+
# urls.py
|
|
39
|
+
urlpatterns = [path("sync/", include("accordsync_django.urls")), ...]
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
The database is `ACCORD_DATABASE_URL` (setting, else environment variable), or else the
|
|
43
|
+
`default` database's settings, which must then use `django.db.backends.postgresql`. The sync
|
|
44
|
+
server uses its own psycopg connection pool, opened on the first request, never Django's ORM
|
|
45
|
+
connections. The views are CSRF-exempt, opt out of `ATOMIC_REQUESTS`, and need no session or auth
|
|
46
|
+
middleware (requests authenticate with the JWT in `Authorization`).
|
|
47
|
+
|
|
48
|
+
`manage.py check` reports `accordsync.E001` when `ACCORD_SERVER` is missing, cannot be imported or
|
|
49
|
+
is not a `ServerDefinition`, and `accordsync.E002` when no PostgreSQL database is configured.
|
|
50
|
+
|
|
51
|
+
```sh
|
|
52
|
+
python manage.py accord_migrate
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Compaction
|
|
56
|
+
|
|
57
|
+
With `compaction.interval_ms > 0` in the definition (default one hour), each process compacts on
|
|
58
|
+
that interval in a background thread started by its first sync request. With several worker
|
|
59
|
+
processes, set `ACCORD_SCHEDULE_COMPACTION = False` and run from cron:
|
|
60
|
+
|
|
61
|
+
```sh
|
|
62
|
+
python manage.py accord_compact
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Notes
|
|
66
|
+
|
|
67
|
+
- Serve with a threaded WSGI server (e.g. waitress, gunicorn `--threads`); each request holds a
|
|
68
|
+
thread while it waits on PostgreSQL.
|
|
69
|
+
- Rate limits are per process (in memory).
|
|
70
|
+
- `examples/django_app` in this repository serves the conformance profile with waitress and
|
|
71
|
+
passes the shared server conformance suite (68/68). Its control API is for tests only
|
|
72
|
+
(`ACCORD_CONTROL=1`).
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# accordsync-django
|
|
2
|
+
|
|
3
|
+
The Accord sync server for Django: an app with the `/v1/push`, `/v1/pull` and `/health` URLs,
|
|
4
|
+
management commands `accord_migrate` and `accord_compact`, and a system check. All behaviour
|
|
5
|
+
comes from `accordsync-server`; this package only routes to it. Part of
|
|
6
|
+
[Accord](https://accord.benhattab.pro).
|
|
7
|
+
|
|
8
|
+
## Install
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
pip install accordsync-django
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Configure
|
|
15
|
+
|
|
16
|
+
```python
|
|
17
|
+
# settings.py
|
|
18
|
+
INSTALLED_APPS = [..., "accordsync_django"]
|
|
19
|
+
ACCORD_SERVER = "myapp.sync:server" # a ServerDefinition made with define_server(...)
|
|
20
|
+
ACCORD_DATABASE_URL = "postgresql://..." # optional, see below
|
|
21
|
+
ACCORD_POOL_SIZE = 20 # optional
|
|
22
|
+
ACCORD_SCHEDULE_COMPACTION = True # optional
|
|
23
|
+
|
|
24
|
+
# urls.py
|
|
25
|
+
urlpatterns = [path("sync/", include("accordsync_django.urls")), ...]
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
The database is `ACCORD_DATABASE_URL` (setting, else environment variable), or else the
|
|
29
|
+
`default` database's settings, which must then use `django.db.backends.postgresql`. The sync
|
|
30
|
+
server uses its own psycopg connection pool, opened on the first request, never Django's ORM
|
|
31
|
+
connections. The views are CSRF-exempt, opt out of `ATOMIC_REQUESTS`, and need no session or auth
|
|
32
|
+
middleware (requests authenticate with the JWT in `Authorization`).
|
|
33
|
+
|
|
34
|
+
`manage.py check` reports `accordsync.E001` when `ACCORD_SERVER` is missing, cannot be imported or
|
|
35
|
+
is not a `ServerDefinition`, and `accordsync.E002` when no PostgreSQL database is configured.
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
python manage.py accord_migrate
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Compaction
|
|
42
|
+
|
|
43
|
+
With `compaction.interval_ms > 0` in the definition (default one hour), each process compacts on
|
|
44
|
+
that interval in a background thread started by its first sync request. With several worker
|
|
45
|
+
processes, set `ACCORD_SCHEDULE_COMPACTION = False` and run from cron:
|
|
46
|
+
|
|
47
|
+
```sh
|
|
48
|
+
python manage.py accord_compact
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Notes
|
|
52
|
+
|
|
53
|
+
- Serve with a threaded WSGI server (e.g. waitress, gunicorn `--threads`); each request holds a
|
|
54
|
+
thread while it waits on PostgreSQL.
|
|
55
|
+
- Rate limits are per process (in memory).
|
|
56
|
+
- `examples/django_app` in this repository serves the conformance profile with waitress and
|
|
57
|
+
passes the shared server conformance suite (68/68). Its control API is for tests only
|
|
58
|
+
(`ACCORD_CONTROL=1`).
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "accordsync-django"
|
|
3
|
+
version = "0.3.0"
|
|
4
|
+
description = "Accord sync server for Django: app, URLs and management commands."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "Apache-2.0"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
requires-python = ">=3.11"
|
|
9
|
+
keywords = ["offline-first", "sync", "crdt", "local-first"]
|
|
10
|
+
dependencies = [
|
|
11
|
+
"accordsync-server>=0.3,<0.4",
|
|
12
|
+
"django>=5.1",
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
[project.urls]
|
|
16
|
+
Homepage = "https://accord.benhattab.pro"
|
|
17
|
+
Source = "https://github.com/crossben/accordsync-python"
|
|
18
|
+
|
|
19
|
+
[build-system]
|
|
20
|
+
requires = ["hatchling>=1.26"]
|
|
21
|
+
build-backend = "hatchling.build"
|
|
22
|
+
|
|
23
|
+
[tool.hatch.build.targets.wheel]
|
|
24
|
+
packages = ["src/accordsync_django"]
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""`manage.py check`: ACCORD_SERVER names a ServerDefinition and a PostgreSQL database is set."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from django.core.checks import CheckMessage, Error, register
|
|
8
|
+
from django.core.exceptions import ImproperlyConfigured
|
|
9
|
+
|
|
10
|
+
from .conf import database_url, load_definition
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@register()
|
|
14
|
+
def check_accord(app_configs: Any = None, **kwargs: Any) -> list[CheckMessage]:
|
|
15
|
+
errors: list[CheckMessage] = []
|
|
16
|
+
try:
|
|
17
|
+
load_definition()
|
|
18
|
+
except ImproperlyConfigured as e:
|
|
19
|
+
errors.append(Error(str(e), id="accordsync.E001"))
|
|
20
|
+
try:
|
|
21
|
+
database_url()
|
|
22
|
+
except ImproperlyConfigured as e:
|
|
23
|
+
errors.append(Error(str(e), id="accordsync.E002"))
|
|
24
|
+
return errors
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Settings: `ACCORD_SERVER` (the definition) and the database the sync server uses.
|
|
2
|
+
|
|
3
|
+
- `ACCORD_SERVER = "module:attribute"` names a `ServerDefinition` (required).
|
|
4
|
+
- `ACCORD_DATABASE_URL` (setting, else environment variable) is a PostgreSQL URL; without it the
|
|
5
|
+
URL is built from `DATABASES["default"]`, which must then use the PostgreSQL backend.
|
|
6
|
+
- `ACCORD_POOL_SIZE` (default 20) and `ACCORD_SCHEDULE_COMPACTION` (default True).
|
|
7
|
+
|
|
8
|
+
The sync server uses its own psycopg pool, never Django's connections (ADR-Y10).
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import atexit
|
|
14
|
+
import importlib
|
|
15
|
+
import logging
|
|
16
|
+
import os
|
|
17
|
+
import threading
|
|
18
|
+
from typing import Any
|
|
19
|
+
from urllib.parse import quote
|
|
20
|
+
|
|
21
|
+
from accordsync_server import AccordServer, ServerDefinition, compact, create_pool
|
|
22
|
+
from django.conf import settings
|
|
23
|
+
from django.core.exceptions import ImproperlyConfigured
|
|
24
|
+
|
|
25
|
+
log = logging.getLogger("accordsync_django")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def load_definition() -> ServerDefinition:
|
|
29
|
+
spec = getattr(settings, "ACCORD_SERVER", None)
|
|
30
|
+
if not spec or not isinstance(spec, str):
|
|
31
|
+
raise ImproperlyConfigured('ACCORD_SERVER must be set to "module:attribute"')
|
|
32
|
+
module, _, attr = spec.partition(":")
|
|
33
|
+
try:
|
|
34
|
+
value = getattr(importlib.import_module(module), attr or "server")
|
|
35
|
+
except (ImportError, AttributeError) as e:
|
|
36
|
+
raise ImproperlyConfigured(f"ACCORD_SERVER {spec!r} cannot be imported: {e}") from e
|
|
37
|
+
if not isinstance(value, ServerDefinition):
|
|
38
|
+
raise ImproperlyConfigured(
|
|
39
|
+
f"ACCORD_SERVER {spec!r} is not a ServerDefinition (use define_server(...))"
|
|
40
|
+
)
|
|
41
|
+
return value
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def database_url() -> str:
|
|
45
|
+
url = getattr(settings, "ACCORD_DATABASE_URL", None) or os.environ.get("ACCORD_DATABASE_URL")
|
|
46
|
+
if url:
|
|
47
|
+
return str(url)
|
|
48
|
+
db: dict[str, Any] = settings.DATABASES.get("default", {})
|
|
49
|
+
if db.get("ENGINE") != "django.db.backends.postgresql":
|
|
50
|
+
raise ImproperlyConfigured(
|
|
51
|
+
"set ACCORD_DATABASE_URL, or use django.db.backends.postgresql for the default database"
|
|
52
|
+
)
|
|
53
|
+
user = quote(str(db.get("USER") or ""), safe="")
|
|
54
|
+
password = quote(str(db.get("PASSWORD") or ""), safe="")
|
|
55
|
+
auth = f"{user}:{password}@" if password else (f"{user}@" if user else "")
|
|
56
|
+
host = str(db.get("HOST") or "localhost")
|
|
57
|
+
port = f":{db['PORT']}" if db.get("PORT") else ""
|
|
58
|
+
return f"postgresql://{auth}{host}{port}/{quote(str(db.get('NAME') or ''), safe='')}"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class _Scheduler:
|
|
62
|
+
def __init__(self, server: AccordServer) -> None:
|
|
63
|
+
self.server = server
|
|
64
|
+
self.interval_s = server.definition.compaction.interval_ms / 1000
|
|
65
|
+
self.stop = threading.Event()
|
|
66
|
+
|
|
67
|
+
def run(self) -> None:
|
|
68
|
+
while not self.stop.wait(self.interval_s):
|
|
69
|
+
try:
|
|
70
|
+
r = compact(self.server.pool, self.server.definition)
|
|
71
|
+
log.info(
|
|
72
|
+
"compaction: %d records, %d ops folded below position %d, %d tombstones pruned",
|
|
73
|
+
r["records"],
|
|
74
|
+
r["opsFolded"],
|
|
75
|
+
r["watermark"],
|
|
76
|
+
r["tombstonesPruned"],
|
|
77
|
+
)
|
|
78
|
+
except Exception:
|
|
79
|
+
log.exception("compaction failed")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
_lock = threading.Lock()
|
|
83
|
+
_server: AccordServer | None = None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def get_server() -> AccordServer:
|
|
87
|
+
"""The process's `AccordServer`, created (pool opened, compaction scheduled) on first use."""
|
|
88
|
+
global _server
|
|
89
|
+
if _server is not None:
|
|
90
|
+
return _server
|
|
91
|
+
with _lock:
|
|
92
|
+
if _server is None:
|
|
93
|
+
server = AccordServer(
|
|
94
|
+
load_definition(),
|
|
95
|
+
create_pool(database_url(), size=int(getattr(settings, "ACCORD_POOL_SIZE", 20))),
|
|
96
|
+
)
|
|
97
|
+
atexit.register(server.pool.close)
|
|
98
|
+
if getattr(settings, "ACCORD_SCHEDULE_COMPACTION", True):
|
|
99
|
+
sched = _Scheduler(server)
|
|
100
|
+
if sched.interval_s > 0:
|
|
101
|
+
threading.Thread(
|
|
102
|
+
target=sched.run, name="accord-compaction", daemon=True
|
|
103
|
+
).start()
|
|
104
|
+
atexit.register(sched.stop.set)
|
|
105
|
+
_server = server
|
|
106
|
+
return _server
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
from accordsync_server import compact, create_pool
|
|
5
|
+
from django.core.management.base import BaseCommand
|
|
6
|
+
|
|
7
|
+
from ...conf import database_url, load_definition
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Command(BaseCommand):
|
|
11
|
+
help = "Runs Accord log compaction once (schedule it with cron for multi-process deployments)."
|
|
12
|
+
|
|
13
|
+
def handle(self, *args: Any, **options: Any) -> None:
|
|
14
|
+
definition = load_definition()
|
|
15
|
+
with create_pool(database_url(), size=2) as pool:
|
|
16
|
+
self.stdout.write(json.dumps(compact(pool, definition)))
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
from accordsync_server import migrate
|
|
4
|
+
from django.core.management.base import BaseCommand
|
|
5
|
+
|
|
6
|
+
from ...conf import database_url
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Command(BaseCommand):
|
|
10
|
+
help = "Applies the Accord migrations to the sync database (shared ledger with every server)."
|
|
11
|
+
|
|
12
|
+
def handle(self, *args: Any, **options: Any) -> None:
|
|
13
|
+
ran = migrate(database_url())
|
|
14
|
+
self.stdout.write(
|
|
15
|
+
f"applied {len(ran)} migration(s): {', '.join(ran)}" if ran else "up to date"
|
|
16
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""`path("", include("accordsync_django.urls"))` serves /v1/push, /v1/pull and /health."""
|
|
2
|
+
|
|
3
|
+
from django.urls import path
|
|
4
|
+
|
|
5
|
+
from . import views
|
|
6
|
+
|
|
7
|
+
app_name = "accordsync"
|
|
8
|
+
urlpatterns = [
|
|
9
|
+
path("v1/push", views.push, name="push"),
|
|
10
|
+
path("v1/pull", views.pull, name="pull"),
|
|
11
|
+
path("health", views.health, name="health"),
|
|
12
|
+
]
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""The three endpoints: each passes the raw request to `AccordServer.handle()` (ADR-Y07)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
|
|
7
|
+
from django.db import transaction
|
|
8
|
+
from django.http import HttpRequest, HttpResponse
|
|
9
|
+
from django.views.decorators.csrf import csrf_exempt
|
|
10
|
+
|
|
11
|
+
from .conf import get_server
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _view(path: str) -> Callable[[HttpRequest], HttpResponse]:
|
|
15
|
+
@csrf_exempt
|
|
16
|
+
@transaction.non_atomic_requests
|
|
17
|
+
def view(request: HttpRequest) -> HttpResponse:
|
|
18
|
+
server = get_server()
|
|
19
|
+
length = request.META.get("CONTENT_LENGTH") or "0"
|
|
20
|
+
try:
|
|
21
|
+
n = int(length)
|
|
22
|
+
except ValueError:
|
|
23
|
+
n = 0
|
|
24
|
+
# Read the stream directly (not request.body: DATA_UPLOAD_MAX_MEMORY_SIZE must not apply),
|
|
25
|
+
# at most one byte past the limit: a larger body gets 413 without being buffered.
|
|
26
|
+
body = request.read(min(n, server.max_body_bytes + 1)) if n > 0 else b""
|
|
27
|
+
res = server.handle(
|
|
28
|
+
request.method or "GET",
|
|
29
|
+
path,
|
|
30
|
+
request.META.get("QUERY_STRING", ""),
|
|
31
|
+
dict(request.headers.items()),
|
|
32
|
+
body,
|
|
33
|
+
)
|
|
34
|
+
out = HttpResponse(res.body, status=res.status)
|
|
35
|
+
merged: dict[str, list[str]] = {}
|
|
36
|
+
for name, value in res.headers:
|
|
37
|
+
merged.setdefault(name, []).append(value)
|
|
38
|
+
for name, values in merged.items():
|
|
39
|
+
out[name] = ", ".join(values)
|
|
40
|
+
return out
|
|
41
|
+
|
|
42
|
+
view.__name__ = "accord_" + path.strip("/").replace("/", "_")
|
|
43
|
+
return view
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
push = _view("/v1/push")
|
|
47
|
+
pull = _view("/v1/pull")
|
|
48
|
+
health = _view("/health")
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
from accordsync_core import define_schema, lww
|
|
2
|
+
from accordsync_server import Access, Auth, Limits, define_server
|
|
3
|
+
|
|
4
|
+
definition = define_server(
|
|
5
|
+
schema=define_schema({"note": {"title": lww()}}),
|
|
6
|
+
scopes={"note": lambda r: ["all"]},
|
|
7
|
+
access=lambda c: Access(read=["all"], write=["all"]),
|
|
8
|
+
auth=Auth.hs256("x" * 32),
|
|
9
|
+
limits=Limits(max_body_bytes=100),
|
|
10
|
+
)
|
|
11
|
+
not_a_definition = 42
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
import django
|
|
5
|
+
from django.conf import settings
|
|
6
|
+
|
|
7
|
+
sys.path.insert(0, str(Path(__file__).parent))
|
|
8
|
+
|
|
9
|
+
if not settings.configured:
|
|
10
|
+
settings.configure(
|
|
11
|
+
INSTALLED_APPS=["accordsync_django"],
|
|
12
|
+
ROOT_URLCONF="accordsync_django.urls",
|
|
13
|
+
ALLOWED_HOSTS=["testserver"],
|
|
14
|
+
DATABASES={},
|
|
15
|
+
MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"],
|
|
16
|
+
ACCORD_SERVER="accordsync_django_testdef:definition",
|
|
17
|
+
)
|
|
18
|
+
django.setup()
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Wiring tests: settings, the system check, commands and views passing requests through."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import pytest
|
|
10
|
+
from accordsync_django import PROTOCOL_VERSION, conf, views
|
|
11
|
+
from accordsync_django.checks import check_accord
|
|
12
|
+
from accordsync_server import AccordServer, Response
|
|
13
|
+
from django.core.exceptions import ImproperlyConfigured
|
|
14
|
+
from django.core.management import call_command, get_commands
|
|
15
|
+
from django.test import Client, override_settings
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class DeadPool:
|
|
19
|
+
def connection(self, **_: Any) -> Any:
|
|
20
|
+
raise RuntimeError("no database")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class StubServer(AccordServer):
|
|
24
|
+
def __init__(self) -> None:
|
|
25
|
+
super().__init__(conf.load_definition(), DeadPool()) # type: ignore[arg-type]
|
|
26
|
+
self.calls: list[tuple[str, str, Any, dict[str, str], bytes]] = []
|
|
27
|
+
|
|
28
|
+
def handle(
|
|
29
|
+
self, method: str, path: str, query: Any, headers: Mapping[str, str], body: bytes = b""
|
|
30
|
+
) -> Response:
|
|
31
|
+
self.calls.append((method, path, query, dict(headers), body))
|
|
32
|
+
return Response(418, [("Content-Type", "text/plain"), ("Vary", "A"), ("Vary", "B")], b"s")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@pytest.fixture
|
|
36
|
+
def stub(monkeypatch: pytest.MonkeyPatch) -> StubServer:
|
|
37
|
+
server = StubServer()
|
|
38
|
+
monkeypatch.setattr(views, "get_server", lambda: server)
|
|
39
|
+
return server
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def test_speaks_protocol_version_1() -> None:
|
|
43
|
+
assert PROTOCOL_VERSION == 1
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_passes_raw_request_and_response_through(stub: StubServer) -> None:
|
|
47
|
+
res = Client().post(
|
|
48
|
+
"/v1/push?a=1&a=2",
|
|
49
|
+
data=b'{"ops": []}',
|
|
50
|
+
content_type="application/json",
|
|
51
|
+
headers={"Accord-Device": "d1"},
|
|
52
|
+
)
|
|
53
|
+
assert res.status_code == 418
|
|
54
|
+
assert res.content == b"s"
|
|
55
|
+
assert res["Vary"] == "A, B"
|
|
56
|
+
method, path, query, headers, body = stub.calls[0]
|
|
57
|
+
assert (method, path, query, body) == ("POST", "/v1/push", "a=1&a=2", b'{"ops": []}')
|
|
58
|
+
assert headers["Accord-Device"] == "d1"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@pytest.mark.parametrize(("url", "path"), [("/v1/pull", "/v1/pull"), ("/health", "/health")])
|
|
62
|
+
@pytest.mark.parametrize("method", ["get", "head", "options", "delete"])
|
|
63
|
+
def test_every_method_reaches_handle(stub: StubServer, url: str, path: str, method: str) -> None:
|
|
64
|
+
assert getattr(Client(), method)(url).status_code == 418
|
|
65
|
+
assert stub.calls[0][:2] == (method.upper(), path)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_body_is_cut_one_byte_past_the_limit(stub: StubServer) -> None:
|
|
69
|
+
Client().post("/v1/push", data=b"x" * 10_000, content_type="application/json")
|
|
70
|
+
assert stub.calls[0][4] == b"x" * 101
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def test_views_are_csrf_exempt_and_not_atomic(stub: StubServer) -> None:
|
|
74
|
+
for view in (views.push, views.pull, views.health):
|
|
75
|
+
assert getattr(view, "csrf_exempt", False)
|
|
76
|
+
assert getattr(view, "_non_atomic_requests", None)
|
|
77
|
+
assert Client(enforce_csrf_checks=True).post("/v1/push").status_code == 418
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def test_check_passes() -> None:
|
|
81
|
+
with override_settings(ACCORD_DATABASE_URL="postgresql://h/db"):
|
|
82
|
+
assert check_accord() == []
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@pytest.mark.parametrize(
|
|
86
|
+
("spec", "message"),
|
|
87
|
+
[
|
|
88
|
+
(None, "must be set"),
|
|
89
|
+
("nope_module:x", "cannot be imported"),
|
|
90
|
+
("accordsync_django_testdef:not_a_definition", "not a ServerDefinition"),
|
|
91
|
+
],
|
|
92
|
+
)
|
|
93
|
+
def test_check_reports_bad_definition(spec: str | None, message: str) -> None:
|
|
94
|
+
with override_settings(ACCORD_SERVER=spec, ACCORD_DATABASE_URL="postgresql://h/db"):
|
|
95
|
+
errors = check_accord()
|
|
96
|
+
assert [e.id for e in errors] == ["accordsync.E001"]
|
|
97
|
+
assert message in errors[0].msg
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def test_database_url_from_django_settings(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
101
|
+
monkeypatch.delenv("ACCORD_DATABASE_URL", raising=False)
|
|
102
|
+
db = {
|
|
103
|
+
"ENGINE": "django.db.backends.postgresql",
|
|
104
|
+
"NAME": "app",
|
|
105
|
+
"USER": "me",
|
|
106
|
+
"PASSWORD": "p@ss",
|
|
107
|
+
"HOST": "db",
|
|
108
|
+
"PORT": "5433",
|
|
109
|
+
}
|
|
110
|
+
with override_settings(DATABASES={"default": db}):
|
|
111
|
+
assert conf.database_url() == "postgresql://me:p%40ss@db:5433/app"
|
|
112
|
+
with override_settings(DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3"}}):
|
|
113
|
+
with pytest.raises(ImproperlyConfigured):
|
|
114
|
+
conf.database_url()
|
|
115
|
+
assert [e.id for e in check_accord()] == ["accordsync.E002"]
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def test_commands_registered() -> None:
|
|
119
|
+
commands = get_commands()
|
|
120
|
+
assert commands["accord_migrate"] == "accordsync_django"
|
|
121
|
+
assert commands["accord_compact"] == "accordsync_django"
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def test_migrate_command_against_postgres() -> None:
|
|
125
|
+
url = os.environ.get("ACCORD_TEST_DATABASE_URL")
|
|
126
|
+
if not url:
|
|
127
|
+
pytest.skip("ACCORD_TEST_DATABASE_URL is not set")
|
|
128
|
+
with override_settings(ACCORD_DATABASE_URL=url):
|
|
129
|
+
call_command("accord_migrate")
|
|
130
|
+
call_command("accord_compact")
|