accordsync-server 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_server-0.3.0/.gitignore +9 -0
- accordsync_server-0.3.0/LICENSE +202 -0
- accordsync_server-0.3.0/PKG-INFO +135 -0
- accordsync_server-0.3.0/README.md +120 -0
- accordsync_server-0.3.0/pyproject.toml +25 -0
- accordsync_server-0.3.0/src/accordsync_server/__init__.py +54 -0
- accordsync_server-0.3.0/src/accordsync_server/__main__.py +50 -0
- accordsync_server-0.3.0/src/accordsync_server/app.py +281 -0
- accordsync_server-0.3.0/src/accordsync_server/auth.py +63 -0
- accordsync_server-0.3.0/src/accordsync_server/compact.py +82 -0
- accordsync_server-0.3.0/src/accordsync_server/db.py +25 -0
- accordsync_server-0.3.0/src/accordsync_server/define.py +165 -0
- accordsync_server-0.3.0/src/accordsync_server/jsnum.py +43 -0
- accordsync_server-0.3.0/src/accordsync_server/migrations.py +213 -0
- accordsync_server-0.3.0/src/accordsync_server/py.typed +0 -0
- accordsync_server-0.3.0/src/accordsync_server/ratelimit.py +64 -0
- accordsync_server-0.3.0/src/accordsync_server/sync.py +577 -0
- accordsync_server-0.3.0/tests/__init__.py +0 -0
- accordsync_server-0.3.0/tests/conftest.py +71 -0
- accordsync_server-0.3.0/tests/test_app.py +146 -0
- accordsync_server-0.3.0/tests/test_auth.py +128 -0
- accordsync_server-0.3.0/tests/test_define.py +85 -0
- accordsync_server-0.3.0/tests/test_jsnum.py +25 -0
- accordsync_server-0.3.0/tests/test_migrations.py +119 -0
- accordsync_server-0.3.0/tests/test_op_hash.py +59 -0
- accordsync_server-0.3.0/tests/test_ratelimit.py +26 -0
- accordsync_server-0.3.0/tests/ts/hash_ops.json +1 -0
- accordsync_server-0.3.0/tests/ts/ts_tool.mts +24 -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,135 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: accordsync-server
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: The Accord sync server for Python on PostgreSQL, framework-agnostic.
|
|
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-core<0.4,>=0.3
|
|
12
|
+
Requires-Dist: psycopg[binary,pool]>=3.2
|
|
13
|
+
Requires-Dist: pyjwt[crypto]>=2.10
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# accordsync-server
|
|
17
|
+
|
|
18
|
+
**The [Accord](https://accord.benhattab.pro) sync server for Python, on PostgreSQL.**
|
|
19
|
+
|
|
20
|
+
Framework-agnostic: push and pull, scopes, JWT auth, limits, rate limits, CORS and compaction behind
|
|
21
|
+
one `handle()` call per request, plus a WSGI application. It speaks the same protocol, merges by the
|
|
22
|
+
same rules and uses the same PostgreSQL schema as
|
|
23
|
+
[`@accordsync/server`](https://www.npmjs.com/package/@accordsync/server), so the TypeScript, React
|
|
24
|
+
Native, Flutter and Python clients sync with it unchanged.
|
|
25
|
+
|
|
26
|
+
With FastAPI or Django, use [`accordsync-fastapi`](https://pypi.org/project/accordsync-fastapi/) or
|
|
27
|
+
[`accordsync-django`](https://pypi.org/project/accordsync-django/): they route to this package. This
|
|
28
|
+
page is for WSGI, or for another framework.
|
|
29
|
+
|
|
30
|
+
## Install
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
pip install accordsync-server
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Python 3.11+ and PostgreSQL (the conformance suite and the example apps use PostgreSQL 16). It
|
|
37
|
+
connects with psycopg 3 and its connection pool.
|
|
38
|
+
|
|
39
|
+
## Define the server
|
|
40
|
+
|
|
41
|
+
`define_server()` takes the same parts as `defineServer` in TypeScript: the schema, a scope function
|
|
42
|
+
per record type, the access a user gets from their JWT claims, and how tokens are checked. It checks
|
|
43
|
+
at once that every record type has a scope function.
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
# myapp/sync.py
|
|
47
|
+
from accordsync_core import conflict, counter, define_schema, lww, set_
|
|
48
|
+
from accordsync_server import Access, Auth, ScopedRecord, define_server
|
|
49
|
+
|
|
50
|
+
schema = define_schema(
|
|
51
|
+
{"dossier": {"agent": lww(), "visits": counter(), "docs": set_(), "status": conflict()}}
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def dossier_scope(record: ScopedRecord) -> list[str]:
|
|
56
|
+
"""The scope keys of a record, from its current fields."""
|
|
57
|
+
agent = record.fields.get("agent")
|
|
58
|
+
return [f"agent:{agent}"] if isinstance(agent, str) else []
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
server = define_server(
|
|
62
|
+
schema=schema,
|
|
63
|
+
scopes={"dossier": dossier_scope},
|
|
64
|
+
# The scope keys a user may read and write, from their verified JWT claims.
|
|
65
|
+
access=lambda claims: Access(read=[f"agent:{claims['sub']}"], write=[f"agent:{claims['sub']}"]),
|
|
66
|
+
auth=Auth.jwks(
|
|
67
|
+
"https://auth.example.com/.well-known/jwks.json",
|
|
68
|
+
issuer="https://auth.example.com/",
|
|
69
|
+
audience="accord",
|
|
70
|
+
),
|
|
71
|
+
)
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Optional arguments: `cors` (browser origins allowed to call the API), `rate_limit` (a `RateLimits`;
|
|
75
|
+
default 600 requests a minute per device and 1 800 per user; `False` turns it off), `compaction` (a
|
|
76
|
+
`Compaction`: device TTL, interval, minimum ops) and `limits` (a `Limits`: body size, concurrent
|
|
77
|
+
pushes, ops per push, pull page size, scope delta size, clock skew). `Auth.hs256(secret)` is for
|
|
78
|
+
development and tests.
|
|
79
|
+
|
|
80
|
+
## Serve it
|
|
81
|
+
|
|
82
|
+
`AccordServer(definition, pool)` serves `GET /health`, `POST /v1/push` and `GET /v1/pull`.
|
|
83
|
+
`server.handle(method, path, query, headers, body)` returns a `Response(status, headers, body)` for
|
|
84
|
+
any framework; `server.wsgi` is a ready WSGI application:
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
# myapp/wsgi.py
|
|
88
|
+
import os
|
|
89
|
+
|
|
90
|
+
from accordsync_server import AccordServer, create_pool
|
|
91
|
+
|
|
92
|
+
from myapp.sync import server as definition
|
|
93
|
+
|
|
94
|
+
app = AccordServer(definition, create_pool(os.environ["ACCORD_DATABASE_URL"])).wsgi
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
`create_pool(url, size=20)` opens a psycopg pool of up to `size` connections. Serve `app` with a
|
|
98
|
+
threaded WSGI server (waitress, or gunicorn with `--threads`): each request holds a thread while it
|
|
99
|
+
waits on PostgreSQL. `ACCORD_DATABASE_URL` is a URL like `postgresql://user:password@host:5432/db`.
|
|
100
|
+
|
|
101
|
+
## Migrations and compaction
|
|
102
|
+
|
|
103
|
+
```sh
|
|
104
|
+
ACCORD_DATABASE_URL=postgresql://… python -m accordsync_server migrate
|
|
105
|
+
ACCORD_DATABASE_URL=postgresql://… python -m accordsync_server compact --definition myapp.sync:server
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Run `compact` from cron at the definition's `compaction.interval_ms` (default hourly). It takes
|
|
109
|
+
PostgreSQL's exclusive advisory lock, so overlapping runs, or several servers, do not conflict. In
|
|
110
|
+
code: `migrate(url)` and `compact(pool, definition)`.
|
|
111
|
+
|
|
112
|
+
## One database, any Accord server
|
|
113
|
+
|
|
114
|
+
The migrations are the TypeScript server's, recorded in the same ledger table (`kysely_migration`):
|
|
115
|
+
a database migrated by `@accordsync/server` is up to date here, and the other way round. One database
|
|
116
|
+
can be served by TypeScript and Python servers at the same time, with clients sent to either. The
|
|
117
|
+
repository's `server-interop/` harness does exactly that: Python and TypeScript devices send every
|
|
118
|
+
request to a randomly chosen server, through a network that loses requests and responses, and must
|
|
119
|
+
end with identical data. This server, and the repository's FastAPI and Django example apps, also
|
|
120
|
+
pass Accord's black-box HTTP conformance suite, the same one the TypeScript server passes.
|
|
121
|
+
|
|
122
|
+
## Security notes
|
|
123
|
+
|
|
124
|
+
- Requests authenticate with `Authorization: Bearer <jwt>`. In production use `Auth.jwks()` with an
|
|
125
|
+
issuer and an audience.
|
|
126
|
+
- Rate limits are kept in memory, per process: with several worker processes, each has its own
|
|
127
|
+
buckets.
|
|
128
|
+
- Request bodies above `limits.max_body_bytes` (default 5 MiB) get 413; the WSGI app stops reading
|
|
129
|
+
past the limit.
|
|
130
|
+
- CORS for the sync API is the definition's `cors` list, answered by the server.
|
|
131
|
+
- What a user may read and write is decided only by your `access` function and scope functions.
|
|
132
|
+
See [docs/security.md](https://github.com/crossben/accordsync/blob/main/docs/security.md).
|
|
133
|
+
|
|
134
|
+
Docs: [accord.benhattab.pro/docs/python](https://accord.benhattab.pro/docs/python/) ·
|
|
135
|
+
Source: [crossben/accordsync-python](https://github.com/crossben/accordsync-python) · Licence: Apache-2.0
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
# accordsync-server
|
|
2
|
+
|
|
3
|
+
**The [Accord](https://accord.benhattab.pro) sync server for Python, on PostgreSQL.**
|
|
4
|
+
|
|
5
|
+
Framework-agnostic: push and pull, scopes, JWT auth, limits, rate limits, CORS and compaction behind
|
|
6
|
+
one `handle()` call per request, plus a WSGI application. It speaks the same protocol, merges by the
|
|
7
|
+
same rules and uses the same PostgreSQL schema as
|
|
8
|
+
[`@accordsync/server`](https://www.npmjs.com/package/@accordsync/server), so the TypeScript, React
|
|
9
|
+
Native, Flutter and Python clients sync with it unchanged.
|
|
10
|
+
|
|
11
|
+
With FastAPI or Django, use [`accordsync-fastapi`](https://pypi.org/project/accordsync-fastapi/) or
|
|
12
|
+
[`accordsync-django`](https://pypi.org/project/accordsync-django/): they route to this package. This
|
|
13
|
+
page is for WSGI, or for another framework.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
pip install accordsync-server
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Python 3.11+ and PostgreSQL (the conformance suite and the example apps use PostgreSQL 16). It
|
|
22
|
+
connects with psycopg 3 and its connection pool.
|
|
23
|
+
|
|
24
|
+
## Define the server
|
|
25
|
+
|
|
26
|
+
`define_server()` takes the same parts as `defineServer` in TypeScript: the schema, a scope function
|
|
27
|
+
per record type, the access a user gets from their JWT claims, and how tokens are checked. It checks
|
|
28
|
+
at once that every record type has a scope function.
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
# myapp/sync.py
|
|
32
|
+
from accordsync_core import conflict, counter, define_schema, lww, set_
|
|
33
|
+
from accordsync_server import Access, Auth, ScopedRecord, define_server
|
|
34
|
+
|
|
35
|
+
schema = define_schema(
|
|
36
|
+
{"dossier": {"agent": lww(), "visits": counter(), "docs": set_(), "status": conflict()}}
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def dossier_scope(record: ScopedRecord) -> list[str]:
|
|
41
|
+
"""The scope keys of a record, from its current fields."""
|
|
42
|
+
agent = record.fields.get("agent")
|
|
43
|
+
return [f"agent:{agent}"] if isinstance(agent, str) else []
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
server = define_server(
|
|
47
|
+
schema=schema,
|
|
48
|
+
scopes={"dossier": dossier_scope},
|
|
49
|
+
# The scope keys a user may read and write, from their verified JWT claims.
|
|
50
|
+
access=lambda claims: Access(read=[f"agent:{claims['sub']}"], write=[f"agent:{claims['sub']}"]),
|
|
51
|
+
auth=Auth.jwks(
|
|
52
|
+
"https://auth.example.com/.well-known/jwks.json",
|
|
53
|
+
issuer="https://auth.example.com/",
|
|
54
|
+
audience="accord",
|
|
55
|
+
),
|
|
56
|
+
)
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Optional arguments: `cors` (browser origins allowed to call the API), `rate_limit` (a `RateLimits`;
|
|
60
|
+
default 600 requests a minute per device and 1 800 per user; `False` turns it off), `compaction` (a
|
|
61
|
+
`Compaction`: device TTL, interval, minimum ops) and `limits` (a `Limits`: body size, concurrent
|
|
62
|
+
pushes, ops per push, pull page size, scope delta size, clock skew). `Auth.hs256(secret)` is for
|
|
63
|
+
development and tests.
|
|
64
|
+
|
|
65
|
+
## Serve it
|
|
66
|
+
|
|
67
|
+
`AccordServer(definition, pool)` serves `GET /health`, `POST /v1/push` and `GET /v1/pull`.
|
|
68
|
+
`server.handle(method, path, query, headers, body)` returns a `Response(status, headers, body)` for
|
|
69
|
+
any framework; `server.wsgi` is a ready WSGI application:
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
# myapp/wsgi.py
|
|
73
|
+
import os
|
|
74
|
+
|
|
75
|
+
from accordsync_server import AccordServer, create_pool
|
|
76
|
+
|
|
77
|
+
from myapp.sync import server as definition
|
|
78
|
+
|
|
79
|
+
app = AccordServer(definition, create_pool(os.environ["ACCORD_DATABASE_URL"])).wsgi
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
`create_pool(url, size=20)` opens a psycopg pool of up to `size` connections. Serve `app` with a
|
|
83
|
+
threaded WSGI server (waitress, or gunicorn with `--threads`): each request holds a thread while it
|
|
84
|
+
waits on PostgreSQL. `ACCORD_DATABASE_URL` is a URL like `postgresql://user:password@host:5432/db`.
|
|
85
|
+
|
|
86
|
+
## Migrations and compaction
|
|
87
|
+
|
|
88
|
+
```sh
|
|
89
|
+
ACCORD_DATABASE_URL=postgresql://… python -m accordsync_server migrate
|
|
90
|
+
ACCORD_DATABASE_URL=postgresql://… python -m accordsync_server compact --definition myapp.sync:server
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Run `compact` from cron at the definition's `compaction.interval_ms` (default hourly). It takes
|
|
94
|
+
PostgreSQL's exclusive advisory lock, so overlapping runs, or several servers, do not conflict. In
|
|
95
|
+
code: `migrate(url)` and `compact(pool, definition)`.
|
|
96
|
+
|
|
97
|
+
## One database, any Accord server
|
|
98
|
+
|
|
99
|
+
The migrations are the TypeScript server's, recorded in the same ledger table (`kysely_migration`):
|
|
100
|
+
a database migrated by `@accordsync/server` is up to date here, and the other way round. One database
|
|
101
|
+
can be served by TypeScript and Python servers at the same time, with clients sent to either. The
|
|
102
|
+
repository's `server-interop/` harness does exactly that: Python and TypeScript devices send every
|
|
103
|
+
request to a randomly chosen server, through a network that loses requests and responses, and must
|
|
104
|
+
end with identical data. This server, and the repository's FastAPI and Django example apps, also
|
|
105
|
+
pass Accord's black-box HTTP conformance suite, the same one the TypeScript server passes.
|
|
106
|
+
|
|
107
|
+
## Security notes
|
|
108
|
+
|
|
109
|
+
- Requests authenticate with `Authorization: Bearer <jwt>`. In production use `Auth.jwks()` with an
|
|
110
|
+
issuer and an audience.
|
|
111
|
+
- Rate limits are kept in memory, per process: with several worker processes, each has its own
|
|
112
|
+
buckets.
|
|
113
|
+
- Request bodies above `limits.max_body_bytes` (default 5 MiB) get 413; the WSGI app stops reading
|
|
114
|
+
past the limit.
|
|
115
|
+
- CORS for the sync API is the definition's `cors` list, answered by the server.
|
|
116
|
+
- What a user may read and write is decided only by your `access` function and scope functions.
|
|
117
|
+
See [docs/security.md](https://github.com/crossben/accordsync/blob/main/docs/security.md).
|
|
118
|
+
|
|
119
|
+
Docs: [accord.benhattab.pro/docs/python](https://accord.benhattab.pro/docs/python/) ·
|
|
120
|
+
Source: [crossben/accordsync-python](https://github.com/crossben/accordsync-python) · Licence: Apache-2.0
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "accordsync-server"
|
|
3
|
+
version = "0.3.0"
|
|
4
|
+
description = "The Accord sync server for Python on PostgreSQL, framework-agnostic."
|
|
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-core>=0.3,<0.4",
|
|
12
|
+
"psycopg[binary,pool]>=3.2",
|
|
13
|
+
"pyjwt[crypto]>=2.10",
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
[project.urls]
|
|
17
|
+
Homepage = "https://accord.benhattab.pro"
|
|
18
|
+
Source = "https://github.com/crossben/accordsync-python"
|
|
19
|
+
|
|
20
|
+
[build-system]
|
|
21
|
+
requires = ["hatchling>=1.26"]
|
|
22
|
+
build-backend = "hatchling.build"
|
|
23
|
+
|
|
24
|
+
[tool.hatch.build.targets.wheel]
|
|
25
|
+
packages = ["src/accordsync_server"]
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""The Accord sync server on PostgreSQL, framework-agnostic: push, pull, scopes, compaction."""
|
|
2
|
+
|
|
3
|
+
from accordsync_core import PROTOCOL_VERSION
|
|
4
|
+
|
|
5
|
+
from .app import AccordServer, Response
|
|
6
|
+
from .auth import AuthError, create_verifier
|
|
7
|
+
from .compact import CompactionResult, compact
|
|
8
|
+
from .db import create_pool
|
|
9
|
+
from .define import (
|
|
10
|
+
Access,
|
|
11
|
+
Auth,
|
|
12
|
+
Claims,
|
|
13
|
+
Compaction,
|
|
14
|
+
Limits,
|
|
15
|
+
RateLimit,
|
|
16
|
+
RateLimits,
|
|
17
|
+
ScopedRecord,
|
|
18
|
+
ServerDefinition,
|
|
19
|
+
define_server,
|
|
20
|
+
)
|
|
21
|
+
from .migrations import migrate
|
|
22
|
+
from .ratelimit import Limiter, RateLimiter
|
|
23
|
+
from .sync import FEED_LOCK, BadRequestError, Caller, ForbiddenError, op_hash, pull, push
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"FEED_LOCK",
|
|
27
|
+
"PROTOCOL_VERSION",
|
|
28
|
+
"Access",
|
|
29
|
+
"AccordServer",
|
|
30
|
+
"Auth",
|
|
31
|
+
"AuthError",
|
|
32
|
+
"BadRequestError",
|
|
33
|
+
"Caller",
|
|
34
|
+
"Claims",
|
|
35
|
+
"Compaction",
|
|
36
|
+
"CompactionResult",
|
|
37
|
+
"ForbiddenError",
|
|
38
|
+
"Limiter",
|
|
39
|
+
"Limits",
|
|
40
|
+
"RateLimit",
|
|
41
|
+
"RateLimiter",
|
|
42
|
+
"RateLimits",
|
|
43
|
+
"Response",
|
|
44
|
+
"ScopedRecord",
|
|
45
|
+
"ServerDefinition",
|
|
46
|
+
"compact",
|
|
47
|
+
"create_pool",
|
|
48
|
+
"create_verifier",
|
|
49
|
+
"define_server",
|
|
50
|
+
"migrate",
|
|
51
|
+
"op_hash",
|
|
52
|
+
"pull",
|
|
53
|
+
"push",
|
|
54
|
+
]
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""`python -m accordsync_server migrate|compact`.
|
|
2
|
+
|
|
3
|
+
`migrate` needs only ACCORD_DATABASE_URL. `compact` also needs the server definition:
|
|
4
|
+
`--definition module:attribute` (or ACCORD_SERVER) naming a `ServerDefinition`.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import importlib
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import sys
|
|
14
|
+
|
|
15
|
+
from .compact import compact
|
|
16
|
+
from .db import create_pool
|
|
17
|
+
from .define import ServerDefinition
|
|
18
|
+
from .migrations import migrate
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def load_definition(spec: str) -> ServerDefinition:
|
|
22
|
+
module, _, attr = spec.partition(":")
|
|
23
|
+
value = getattr(importlib.import_module(module), attr or "server")
|
|
24
|
+
if not isinstance(value, ServerDefinition):
|
|
25
|
+
raise SystemExit(f"{spec} is not a ServerDefinition (use define_server(...))")
|
|
26
|
+
return value
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def main(argv: list[str] | None = None) -> int:
|
|
30
|
+
parser = argparse.ArgumentParser(prog="python -m accordsync_server")
|
|
31
|
+
parser.add_argument("command", choices=["migrate", "compact"])
|
|
32
|
+
parser.add_argument("--database-url", default=os.environ.get("ACCORD_DATABASE_URL"))
|
|
33
|
+
parser.add_argument("--definition", default=os.environ.get("ACCORD_SERVER"))
|
|
34
|
+
args = parser.parse_args(argv)
|
|
35
|
+
if not args.database_url:
|
|
36
|
+
parser.error("ACCORD_DATABASE_URL (or --database-url) is required")
|
|
37
|
+
if args.command == "migrate":
|
|
38
|
+
ran = migrate(args.database_url)
|
|
39
|
+
print(f"applied {len(ran)} migration(s): {', '.join(ran)}" if ran else "up to date")
|
|
40
|
+
return 0
|
|
41
|
+
if not args.definition:
|
|
42
|
+
parser.error("compact needs --definition module:attribute (or ACCORD_SERVER)")
|
|
43
|
+
definition = load_definition(args.definition)
|
|
44
|
+
with create_pool(args.database_url, size=2) as pool:
|
|
45
|
+
print(json.dumps(compact(pool, definition)))
|
|
46
|
+
return 0
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
if __name__ == "__main__":
|
|
50
|
+
sys.exit(main())
|