lattice-grid 0.1.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.
- lattice_grid-0.1.0/.gitignore +8 -0
- lattice_grid-0.1.0/LICENSE +21 -0
- lattice_grid-0.1.0/PKG-INFO +192 -0
- lattice_grid-0.1.0/README.md +169 -0
- lattice_grid-0.1.0/hatch_build.py +23 -0
- lattice_grid-0.1.0/pyproject.toml +63 -0
- lattice_grid-0.1.0/src/lattice_grid/__init__.py +59 -0
- lattice_grid-0.1.0/src/lattice_grid/collab/__init__.py +31 -0
- lattice_grid-0.1.0/src/lattice_grid/collab/asgi.py +84 -0
- lattice_grid-0.1.0/src/lattice_grid/collab/engine.py +21 -0
- lattice_grid-0.1.0/src/lattice_grid/collab/ironcalc.py +406 -0
- lattice_grid-0.1.0/src/lattice_grid/collab/ironcalc.wasm +0 -0
- lattice_grid-0.1.0/src/lattice_grid/collab/model.py +419 -0
- lattice_grid-0.1.0/src/lattice_grid/collab/refs.py +243 -0
- lattice_grid-0.1.0/src/lattice_grid/collab/server.py +328 -0
- lattice_grid-0.1.0/src/lattice_grid/collab/store.py +62 -0
- lattice_grid-0.1.0/src/lattice_grid/collab/wire.py +371 -0
- lattice_grid-0.1.0/src/lattice_grid/protocol.py +727 -0
- lattice_grid-0.1.0/src/lattice_grid/py.typed +0 -0
- lattice_grid-0.1.0/src/lattice_grid/sqlalchemy.py +708 -0
- lattice_grid-0.1.0/tests/__init__.py +0 -0
- lattice_grid-0.1.0/tests/conformance.py +85 -0
- lattice_grid-0.1.0/tests/conftest.py +74 -0
- lattice_grid-0.1.0/tests/fixtures/collab.json +8363 -0
- lattice_grid-0.1.0/tests/fixtures/collab_fixture.mjs +93 -0
- lattice_grid-0.1.0/tests/fixtures/collab_scenarios.mjs +339 -0
- lattice_grid-0.1.0/tests/test_collab_asgi.py +116 -0
- lattice_grid-0.1.0/tests/test_collab_bench.py +56 -0
- lattice_grid-0.1.0/tests/test_collab_cross.py +85 -0
- lattice_grid-0.1.0/tests/test_collab_engine.py +79 -0
- lattice_grid-0.1.0/tests/test_collab_server.py +494 -0
- lattice_grid-0.1.0/tests/test_collab_wire.py +235 -0
- lattice_grid-0.1.0/tests/test_conformance.py +57 -0
- lattice_grid-0.1.0/tests/test_parse.py +496 -0
- lattice_grid-0.1.0/tests/test_security.py +183 -0
- lattice_grid-0.1.0/tests/test_sqlalchemy.py +278 -0
- lattice_grid-0.1.0/uv.lock +707 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Joe Gaudet
|
|
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,192 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: lattice-grid
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: The Lattice grid wire protocol for Python servers: a parser, a SQLAlchemy query layer and the collab op log server.
|
|
5
|
+
Project-URL: Homepage, https://joegaudet.com/ember-lattice/
|
|
6
|
+
Project-URL: Source, https://github.com/joegaudet/ember-lattice/tree/main/python/lattice-grid
|
|
7
|
+
Project-URL: Issues, https://github.com/joegaudet/ember-lattice/issues
|
|
8
|
+
Author-email: Joe Gaudet <joe@joegaudet.com>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Classifier: Typing :: Typed
|
|
12
|
+
Requires-Python: >=3.11
|
|
13
|
+
Provides-Extra: collab
|
|
14
|
+
Requires-Dist: wasmtime>=51; extra == 'collab'
|
|
15
|
+
Provides-Extra: django
|
|
16
|
+
Requires-Dist: sqlalchemy>=2.0; extra == 'django'
|
|
17
|
+
Provides-Extra: postgres
|
|
18
|
+
Requires-Dist: psycopg[binary]>=3.1; extra == 'postgres'
|
|
19
|
+
Requires-Dist: sqlalchemy>=2.0; extra == 'postgres'
|
|
20
|
+
Provides-Extra: sqlalchemy
|
|
21
|
+
Requires-Dist: sqlalchemy>=2.0; extra == 'sqlalchemy'
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# lattice-grid (Python)
|
|
25
|
+
|
|
26
|
+
The Python server for the Lattice wire protocol, version 1. It reads a grid request, checks it
|
|
27
|
+
against an allow-list, and answers it with SQLAlchemy 2 Core. The protocol and its rules are in
|
|
28
|
+
[ADR 0005](https://joegaudet.com/ember-lattice/docs/adr/0005-wire-protocol/index.html).
|
|
29
|
+
|
|
30
|
+
Part of [Lattice](https://joegaudet.com/ember-lattice/). Not released yet.
|
|
31
|
+
|
|
32
|
+
## Install
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install "lattice-grid[sqlalchemy]" # SQLAlchemy only
|
|
36
|
+
pip install "lattice-grid[postgres]" # SQLAlchemy and psycopg
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
The parser has no dependencies. Python 3.11 or later.
|
|
40
|
+
|
|
41
|
+
## The parser
|
|
42
|
+
|
|
43
|
+
`parse_rows_request(data, columns)` is the trust boundary. It is a port of the TypeScript
|
|
44
|
+
`parseRowsRequest`, with the same limits, error codes, paths and messages. It never raises. It
|
|
45
|
+
returns a `ParseResult`: `value` is a frozen `RowsRequest`, or `errors` holds the issues.
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
from lattice_grid import parse_rows_request
|
|
49
|
+
|
|
50
|
+
result = parse_rows_request(json.loads(body), columns)
|
|
51
|
+
if not result.ok:
|
|
52
|
+
return 400, {"errors": [e.to_dict() for e in result.errors]}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Limit the request body size before you parse it.
|
|
56
|
+
|
|
57
|
+
## The SQLAlchemy query
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
import sqlalchemy as sa
|
|
61
|
+
from lattice_grid.sqlalchemy import RowsQuery
|
|
62
|
+
|
|
63
|
+
columns = [
|
|
64
|
+
{"name": "id", "type": "number", "key": True, "sort": True},
|
|
65
|
+
{"name": "name", "type": "string", "filter": ["eq", "contains"], "sort": True, "search": True},
|
|
66
|
+
{"name": "dept", "type": "string", "group": True, "aggregate": ["count"]},
|
|
67
|
+
{"name": "salary", "type": "number", "filter": ["gt", "lt"], "aggregate": ["sum", "avg"]},
|
|
68
|
+
]
|
|
69
|
+
people = RowsQuery(people_table, columns=columns)
|
|
70
|
+
|
|
71
|
+
with engine.connect() as conn:
|
|
72
|
+
body = people.respond(json.loads(request_body), conn)
|
|
73
|
+
status = 400 if "errors" in body else 200
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
- The source is a `Table` or a `Select`. Use a `Select` to limit the rows that a user can see.
|
|
77
|
+
- `columns` is the allow-list, with the same shape as the TypeScript `ColumnSchema`. Each name
|
|
78
|
+
must be a column of the source.
|
|
79
|
+
- `key="id"` names the row id column. Cursor paging needs a key.
|
|
80
|
+
- `RowsQuery(...)(data, conn)` returns the response dict, and raises
|
|
81
|
+
`ProtocolValidationError` for a bad request or a bad cursor.
|
|
82
|
+
- `RowsQuery.respond(data, conn)` returns the HTTP body: the response, or `{"errors": [...]}`.
|
|
83
|
+
It does not need a web framework.
|
|
84
|
+
|
|
85
|
+
The query does filters, quick search, sort with null order, group rows with aggregates and
|
|
86
|
+
`$count`, leaf rows under group keys, pivot, offset and cursor paging, `count` and the grand
|
|
87
|
+
total. Postgres uses `FILTER (WHERE ...)` for pivot cells. Other databases use `CASE`.
|
|
88
|
+
|
|
89
|
+
### Security
|
|
90
|
+
|
|
91
|
+
- Only allow-listed column names go into SQL, as SQLAlchemy columns.
|
|
92
|
+
- Every client value is a bound parameter: filter values, group keys, search text and cursor
|
|
93
|
+
values. The query never uses `text()`.
|
|
94
|
+
- Every SQL label is a name that the query makes (`c0`, `a1`, `p2`). An aggregate `as` never
|
|
95
|
+
goes into SQL.
|
|
96
|
+
- The query checks each cursor value against the type of its sort column.
|
|
97
|
+
- The parser rejects every string that holds U+0000 (`bad_string`). Postgres cannot store it.
|
|
98
|
+
- Before it builds the pivot SQL, the query counts the distinct `pivot.by` values. When there
|
|
99
|
+
are more than 200, it rejects the request with `pivot_too_wide`.
|
|
100
|
+
|
|
101
|
+
### Database rules
|
|
102
|
+
|
|
103
|
+
- Strings sort in binary order: `COLLATE "C"` on Postgres, `BINARY` on SQLite, `utf8mb4_bin`
|
|
104
|
+
on MySQL. On MySQL, `eq`, `in` and groups use the collation of the column. Use a binary
|
|
105
|
+
collation on the column to make `eq` case-sensitive. The tests do not run on MySQL yet.
|
|
106
|
+
- SQLite must be version 3.30 or later, for `NULLS LAST`.
|
|
107
|
+
- Nulls are last by default, in both directions. MySQL does not have `NULLS LAST`, so the query
|
|
108
|
+
sorts by `col IS NULL` first.
|
|
109
|
+
- `contains`, `startsWith` and `endsWith` ignore case, and `%`, `_` and `\` are literal.
|
|
110
|
+
- Use a `Date` or `DateTime` column for a `date` protocol column. On a `Date` column, a date-time
|
|
111
|
+
value that is not midnight UTC gets the correct bounds (for example, `gte 2021-11-30T12:00Z`
|
|
112
|
+
is `>= 2021-12-01`). A naive `DateTime` column holds UTC.
|
|
113
|
+
|
|
114
|
+
## Django
|
|
115
|
+
|
|
116
|
+
There is no `QuerySet` adapter yet. A thin adapter must compile a `QuerySet` into SQLAlchemy, or
|
|
117
|
+
it must use a second query engine on the Django ORM that also passes the conformance suite.
|
|
118
|
+
Django apps use the SQLAlchemy path. Make a SQLAlchemy engine with the database settings of the
|
|
119
|
+
Django app. Then make a `Table` with the columns of the model:
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
table = sa.Table(Person._meta.db_table, sa.MetaData(), autoload_with=engine)
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
## The collab server
|
|
126
|
+
|
|
127
|
+
`lattice_grid.collab` is a port of the Node op log server (`createDocServer`, ADR 0016). It has
|
|
128
|
+
the same wire format, the same limits and error messages, and the same conflict rules. The
|
|
129
|
+
tests compare it with the Node server on a shared fixture.
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
from lattice_grid.collab import DocServer, MemoryStore
|
|
133
|
+
from lattice_grid.collab.asgi import CollabWebSocket
|
|
134
|
+
from lattice_grid.collab.ironcalc import IronCalcEngine
|
|
135
|
+
|
|
136
|
+
server = DocServer(store=MemoryStore(), engine=IronCalcEngine)
|
|
137
|
+
await server.create("d1", {"sheets": [...]})
|
|
138
|
+
app = CollabWebSocket(server, max_bytes=1_000_000) # a plain ASGI app
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
- `parse_client_message(data)` is the trust boundary. It never raises.
|
|
142
|
+
- `DocServer.connect(send)` gives a `Connection`. Call `receive(message)` for each message, in
|
|
143
|
+
order, and `close()` at the end. `send` gets each server message as a dict.
|
|
144
|
+
- `CollabStore` is a protocol with async methods. `MemoryStore` is for tests and one process.
|
|
145
|
+
- `CollabWebSocket` is an ASGI app for the `websocket` scope. Mount it in Starlette with
|
|
146
|
+
`WebSocketRoute("/collab", app)`. Authenticate the socket before it gets to the app: the
|
|
147
|
+
server trusts the client ID of the join.
|
|
148
|
+
|
|
149
|
+
### The formula engine
|
|
150
|
+
|
|
151
|
+
`IronCalcEngine` runs the IronCalc WASI module of ADR 0007 and ADR 0020 with `wasmtime`.
|
|
152
|
+
Install the `collab` extra. The wheel has the module. The engine finds it in this order:
|
|
153
|
+
|
|
154
|
+
1. `IronCalcEngine(wasm=path_or_bytes)`.
|
|
155
|
+
2. The `LATTICE_IRONCALC_WASM` environment variable.
|
|
156
|
+
3. The file `lattice_grid/collab/ironcalc.wasm` in the package.
|
|
157
|
+
|
|
158
|
+
The process compiles the module one time (about 1 s). The engine keeps the workbook between
|
|
159
|
+
submits and applies each submit with one `ic_apply_batch` call: about 5 ms for each submit at
|
|
160
|
+
10,000 cells. The recalc runs in the event loop.
|
|
161
|
+
|
|
162
|
+
To make the shared fixture again after a change to the Node server, run this command from the
|
|
163
|
+
repo root:
|
|
164
|
+
|
|
165
|
+
```bash
|
|
166
|
+
volta run --node 24.11.1 node python/lattice-grid/tests/fixtures/collab_fixture.mjs
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
## Checks
|
|
170
|
+
|
|
171
|
+
The collab tests need the IronCalc module. Build it first; the tests find it in `target/`. The
|
|
172
|
+
sdist and wheel builds need the module in the package, so copy it there, as CI does:
|
|
173
|
+
|
|
174
|
+
```bash
|
|
175
|
+
(cd ../../wasm/ironcalc-wasi && cargo build --release --target wasm32-wasip1)
|
|
176
|
+
cp ../../wasm/ironcalc-wasi/target/wasm32-wasip1/release/ironcalc_wasi.wasm src/lattice_grid/collab/ironcalc.wasm
|
|
177
|
+
python3.11 -m venv .venv
|
|
178
|
+
.venv/bin/pip install -e '.[collab]' sqlalchemy "psycopg[binary]" pytest hypothesis ruff mypy build
|
|
179
|
+
.venv/bin/ruff check
|
|
180
|
+
.venv/bin/ruff format --check
|
|
181
|
+
.venv/bin/mypy
|
|
182
|
+
.venv/bin/pytest
|
|
183
|
+
.venv/bin/python -m build
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
The tests run every case of `packages/protocol/conformance/cases.v1.json` on SQLite. To run
|
|
187
|
+
them on Postgres also, set `LATTICE_TEST_POSTGRES_URL`. The database name must start with
|
|
188
|
+
`lattice_test_py`. The tests make that database and drop it after the run.
|
|
189
|
+
|
|
190
|
+
```bash
|
|
191
|
+
LATTICE_TEST_POSTGRES_URL='postgresql+psycopg://user@/lattice_test_py?host=/tmp' .venv/bin/pytest
|
|
192
|
+
```
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
# lattice-grid (Python)
|
|
2
|
+
|
|
3
|
+
The Python server for the Lattice wire protocol, version 1. It reads a grid request, checks it
|
|
4
|
+
against an allow-list, and answers it with SQLAlchemy 2 Core. The protocol and its rules are in
|
|
5
|
+
[ADR 0005](https://joegaudet.com/ember-lattice/docs/adr/0005-wire-protocol/index.html).
|
|
6
|
+
|
|
7
|
+
Part of [Lattice](https://joegaudet.com/ember-lattice/). Not released yet.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pip install "lattice-grid[sqlalchemy]" # SQLAlchemy only
|
|
13
|
+
pip install "lattice-grid[postgres]" # SQLAlchemy and psycopg
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
The parser has no dependencies. Python 3.11 or later.
|
|
17
|
+
|
|
18
|
+
## The parser
|
|
19
|
+
|
|
20
|
+
`parse_rows_request(data, columns)` is the trust boundary. It is a port of the TypeScript
|
|
21
|
+
`parseRowsRequest`, with the same limits, error codes, paths and messages. It never raises. It
|
|
22
|
+
returns a `ParseResult`: `value` is a frozen `RowsRequest`, or `errors` holds the issues.
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
from lattice_grid import parse_rows_request
|
|
26
|
+
|
|
27
|
+
result = parse_rows_request(json.loads(body), columns)
|
|
28
|
+
if not result.ok:
|
|
29
|
+
return 400, {"errors": [e.to_dict() for e in result.errors]}
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Limit the request body size before you parse it.
|
|
33
|
+
|
|
34
|
+
## The SQLAlchemy query
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
import sqlalchemy as sa
|
|
38
|
+
from lattice_grid.sqlalchemy import RowsQuery
|
|
39
|
+
|
|
40
|
+
columns = [
|
|
41
|
+
{"name": "id", "type": "number", "key": True, "sort": True},
|
|
42
|
+
{"name": "name", "type": "string", "filter": ["eq", "contains"], "sort": True, "search": True},
|
|
43
|
+
{"name": "dept", "type": "string", "group": True, "aggregate": ["count"]},
|
|
44
|
+
{"name": "salary", "type": "number", "filter": ["gt", "lt"], "aggregate": ["sum", "avg"]},
|
|
45
|
+
]
|
|
46
|
+
people = RowsQuery(people_table, columns=columns)
|
|
47
|
+
|
|
48
|
+
with engine.connect() as conn:
|
|
49
|
+
body = people.respond(json.loads(request_body), conn)
|
|
50
|
+
status = 400 if "errors" in body else 200
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
- The source is a `Table` or a `Select`. Use a `Select` to limit the rows that a user can see.
|
|
54
|
+
- `columns` is the allow-list, with the same shape as the TypeScript `ColumnSchema`. Each name
|
|
55
|
+
must be a column of the source.
|
|
56
|
+
- `key="id"` names the row id column. Cursor paging needs a key.
|
|
57
|
+
- `RowsQuery(...)(data, conn)` returns the response dict, and raises
|
|
58
|
+
`ProtocolValidationError` for a bad request or a bad cursor.
|
|
59
|
+
- `RowsQuery.respond(data, conn)` returns the HTTP body: the response, or `{"errors": [...]}`.
|
|
60
|
+
It does not need a web framework.
|
|
61
|
+
|
|
62
|
+
The query does filters, quick search, sort with null order, group rows with aggregates and
|
|
63
|
+
`$count`, leaf rows under group keys, pivot, offset and cursor paging, `count` and the grand
|
|
64
|
+
total. Postgres uses `FILTER (WHERE ...)` for pivot cells. Other databases use `CASE`.
|
|
65
|
+
|
|
66
|
+
### Security
|
|
67
|
+
|
|
68
|
+
- Only allow-listed column names go into SQL, as SQLAlchemy columns.
|
|
69
|
+
- Every client value is a bound parameter: filter values, group keys, search text and cursor
|
|
70
|
+
values. The query never uses `text()`.
|
|
71
|
+
- Every SQL label is a name that the query makes (`c0`, `a1`, `p2`). An aggregate `as` never
|
|
72
|
+
goes into SQL.
|
|
73
|
+
- The query checks each cursor value against the type of its sort column.
|
|
74
|
+
- The parser rejects every string that holds U+0000 (`bad_string`). Postgres cannot store it.
|
|
75
|
+
- Before it builds the pivot SQL, the query counts the distinct `pivot.by` values. When there
|
|
76
|
+
are more than 200, it rejects the request with `pivot_too_wide`.
|
|
77
|
+
|
|
78
|
+
### Database rules
|
|
79
|
+
|
|
80
|
+
- Strings sort in binary order: `COLLATE "C"` on Postgres, `BINARY` on SQLite, `utf8mb4_bin`
|
|
81
|
+
on MySQL. On MySQL, `eq`, `in` and groups use the collation of the column. Use a binary
|
|
82
|
+
collation on the column to make `eq` case-sensitive. The tests do not run on MySQL yet.
|
|
83
|
+
- SQLite must be version 3.30 or later, for `NULLS LAST`.
|
|
84
|
+
- Nulls are last by default, in both directions. MySQL does not have `NULLS LAST`, so the query
|
|
85
|
+
sorts by `col IS NULL` first.
|
|
86
|
+
- `contains`, `startsWith` and `endsWith` ignore case, and `%`, `_` and `\` are literal.
|
|
87
|
+
- Use a `Date` or `DateTime` column for a `date` protocol column. On a `Date` column, a date-time
|
|
88
|
+
value that is not midnight UTC gets the correct bounds (for example, `gte 2021-11-30T12:00Z`
|
|
89
|
+
is `>= 2021-12-01`). A naive `DateTime` column holds UTC.
|
|
90
|
+
|
|
91
|
+
## Django
|
|
92
|
+
|
|
93
|
+
There is no `QuerySet` adapter yet. A thin adapter must compile a `QuerySet` into SQLAlchemy, or
|
|
94
|
+
it must use a second query engine on the Django ORM that also passes the conformance suite.
|
|
95
|
+
Django apps use the SQLAlchemy path. Make a SQLAlchemy engine with the database settings of the
|
|
96
|
+
Django app. Then make a `Table` with the columns of the model:
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
table = sa.Table(Person._meta.db_table, sa.MetaData(), autoload_with=engine)
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## The collab server
|
|
103
|
+
|
|
104
|
+
`lattice_grid.collab` is a port of the Node op log server (`createDocServer`, ADR 0016). It has
|
|
105
|
+
the same wire format, the same limits and error messages, and the same conflict rules. The
|
|
106
|
+
tests compare it with the Node server on a shared fixture.
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
from lattice_grid.collab import DocServer, MemoryStore
|
|
110
|
+
from lattice_grid.collab.asgi import CollabWebSocket
|
|
111
|
+
from lattice_grid.collab.ironcalc import IronCalcEngine
|
|
112
|
+
|
|
113
|
+
server = DocServer(store=MemoryStore(), engine=IronCalcEngine)
|
|
114
|
+
await server.create("d1", {"sheets": [...]})
|
|
115
|
+
app = CollabWebSocket(server, max_bytes=1_000_000) # a plain ASGI app
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
- `parse_client_message(data)` is the trust boundary. It never raises.
|
|
119
|
+
- `DocServer.connect(send)` gives a `Connection`. Call `receive(message)` for each message, in
|
|
120
|
+
order, and `close()` at the end. `send` gets each server message as a dict.
|
|
121
|
+
- `CollabStore` is a protocol with async methods. `MemoryStore` is for tests and one process.
|
|
122
|
+
- `CollabWebSocket` is an ASGI app for the `websocket` scope. Mount it in Starlette with
|
|
123
|
+
`WebSocketRoute("/collab", app)`. Authenticate the socket before it gets to the app: the
|
|
124
|
+
server trusts the client ID of the join.
|
|
125
|
+
|
|
126
|
+
### The formula engine
|
|
127
|
+
|
|
128
|
+
`IronCalcEngine` runs the IronCalc WASI module of ADR 0007 and ADR 0020 with `wasmtime`.
|
|
129
|
+
Install the `collab` extra. The wheel has the module. The engine finds it in this order:
|
|
130
|
+
|
|
131
|
+
1. `IronCalcEngine(wasm=path_or_bytes)`.
|
|
132
|
+
2. The `LATTICE_IRONCALC_WASM` environment variable.
|
|
133
|
+
3. The file `lattice_grid/collab/ironcalc.wasm` in the package.
|
|
134
|
+
|
|
135
|
+
The process compiles the module one time (about 1 s). The engine keeps the workbook between
|
|
136
|
+
submits and applies each submit with one `ic_apply_batch` call: about 5 ms for each submit at
|
|
137
|
+
10,000 cells. The recalc runs in the event loop.
|
|
138
|
+
|
|
139
|
+
To make the shared fixture again after a change to the Node server, run this command from the
|
|
140
|
+
repo root:
|
|
141
|
+
|
|
142
|
+
```bash
|
|
143
|
+
volta run --node 24.11.1 node python/lattice-grid/tests/fixtures/collab_fixture.mjs
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
## Checks
|
|
147
|
+
|
|
148
|
+
The collab tests need the IronCalc module. Build it first; the tests find it in `target/`. The
|
|
149
|
+
sdist and wheel builds need the module in the package, so copy it there, as CI does:
|
|
150
|
+
|
|
151
|
+
```bash
|
|
152
|
+
(cd ../../wasm/ironcalc-wasi && cargo build --release --target wasm32-wasip1)
|
|
153
|
+
cp ../../wasm/ironcalc-wasi/target/wasm32-wasip1/release/ironcalc_wasi.wasm src/lattice_grid/collab/ironcalc.wasm
|
|
154
|
+
python3.11 -m venv .venv
|
|
155
|
+
.venv/bin/pip install -e '.[collab]' sqlalchemy "psycopg[binary]" pytest hypothesis ruff mypy build
|
|
156
|
+
.venv/bin/ruff check
|
|
157
|
+
.venv/bin/ruff format --check
|
|
158
|
+
.venv/bin/mypy
|
|
159
|
+
.venv/bin/pytest
|
|
160
|
+
.venv/bin/python -m build
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
The tests run every case of `packages/protocol/conformance/cases.v1.json` on SQLite. To run
|
|
164
|
+
them on Postgres also, set `LATTICE_TEST_POSTGRES_URL`. The database name must start with
|
|
165
|
+
`lattice_test_py`. The tests make that database and drop it after the run.
|
|
166
|
+
|
|
167
|
+
```bash
|
|
168
|
+
LATTICE_TEST_POSTGRES_URL='postgresql+psycopg://user@/lattice_test_py?host=/tmp' .venv/bin/pytest
|
|
169
|
+
```
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Stops a sdist or wheel build that does not have the IronCalc module (ADR 0020).
|
|
2
|
+
|
|
3
|
+
An editable install (``pip install -e .``) does not need the file: the tests give the path in
|
|
4
|
+
``LATTICE_IRONCALC_WASM``.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from hatchling.builders.hooks.plugin.interface import BuildHookInterface
|
|
11
|
+
|
|
12
|
+
WASM = "src/lattice_grid/collab/ironcalc.wasm"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class CustomBuildHook(BuildHookInterface):
|
|
16
|
+
def initialize(self, version: str, build_data: dict[str, Any]) -> None:
|
|
17
|
+
if version == "editable" or (Path(self.root) / WASM).is_file():
|
|
18
|
+
return
|
|
19
|
+
raise FileNotFoundError(
|
|
20
|
+
f"lattice-grid: {WASM} is missing. Run `cargo build --release --target "
|
|
21
|
+
"wasm32-wasip1` in wasm/ironcalc-wasi and copy "
|
|
22
|
+
f"target/wasm32-wasip1/release/ironcalc_wasi.wasm to {WASM}."
|
|
23
|
+
)
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "lattice-grid"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "The Lattice grid wire protocol for Python servers: a parser, a SQLAlchemy query layer and the collab op log server."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
authors = [{ name = "Joe Gaudet", email = "joe@joegaudet.com" }]
|
|
9
|
+
requires-python = ">=3.11"
|
|
10
|
+
dependencies = []
|
|
11
|
+
classifiers = ["Typing :: Typed"]
|
|
12
|
+
|
|
13
|
+
[project.optional-dependencies]
|
|
14
|
+
sqlalchemy = ["sqlalchemy>=2.0"]
|
|
15
|
+
# There is no QuerySet adapter yet. Django apps use the SQLAlchemy path (see the README).
|
|
16
|
+
django = ["sqlalchemy>=2.0"]
|
|
17
|
+
postgres = ["sqlalchemy>=2.0", "psycopg[binary]>=3.1"]
|
|
18
|
+
# The collab server runs the IronCalc WASI module (ADR 0007, ADR 0020). The wheel has the .wasm.
|
|
19
|
+
collab = ["wasmtime>=51"]
|
|
20
|
+
|
|
21
|
+
[project.urls]
|
|
22
|
+
Homepage = "https://joegaudet.com/ember-lattice/"
|
|
23
|
+
Source = "https://github.com/joegaudet/ember-lattice/tree/main/python/lattice-grid"
|
|
24
|
+
Issues = "https://github.com/joegaudet/ember-lattice/issues"
|
|
25
|
+
|
|
26
|
+
[build-system]
|
|
27
|
+
requires = ["hatchling>=1.27"]
|
|
28
|
+
build-backend = "hatchling.build"
|
|
29
|
+
|
|
30
|
+
# The IronCalc module is not in git (ADR 0020): CI builds it, and the release build copies it to
|
|
31
|
+
# this path. `artifacts` puts the ignored file in the package; hatch_build.py stops a build without it.
|
|
32
|
+
[tool.hatch.build.targets.wheel]
|
|
33
|
+
artifacts = ["src/lattice_grid/collab/ironcalc.wasm"]
|
|
34
|
+
|
|
35
|
+
[tool.hatch.build.targets.sdist]
|
|
36
|
+
artifacts = ["src/lattice_grid/collab/ironcalc.wasm"]
|
|
37
|
+
|
|
38
|
+
[tool.hatch.build.hooks.custom]
|
|
39
|
+
|
|
40
|
+
[dependency-groups]
|
|
41
|
+
dev = [
|
|
42
|
+
"hypothesis>=6.100",
|
|
43
|
+
"mypy>=1.15",
|
|
44
|
+
"psycopg[binary]>=3.1",
|
|
45
|
+
"pytest>=8.3",
|
|
46
|
+
"ruff>=0.11",
|
|
47
|
+
"sqlalchemy>=2.0",
|
|
48
|
+
"wasmtime>=51",
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
[tool.ruff]
|
|
52
|
+
target-version = "py311"
|
|
53
|
+
line-length = 100
|
|
54
|
+
|
|
55
|
+
[tool.ruff.lint]
|
|
56
|
+
select = ["E", "F", "W", "I", "B", "UP", "SIM", "RUF"]
|
|
57
|
+
|
|
58
|
+
[tool.mypy]
|
|
59
|
+
strict = true
|
|
60
|
+
files = ["src", "tests"]
|
|
61
|
+
|
|
62
|
+
[tool.pytest.ini_options]
|
|
63
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Lattice grid wire protocol for Python servers."""
|
|
2
|
+
|
|
3
|
+
from lattice_grid.protocol import (
|
|
4
|
+
AGGREGATE_FNS,
|
|
5
|
+
FILTER_OPS,
|
|
6
|
+
GROUP_COUNT_KEY,
|
|
7
|
+
LIMITS,
|
|
8
|
+
PROTOCOL_VERSION,
|
|
9
|
+
TREE_PATH_SEPARATOR,
|
|
10
|
+
Aggregate,
|
|
11
|
+
And,
|
|
12
|
+
CursorRange,
|
|
13
|
+
FilterNode,
|
|
14
|
+
Group,
|
|
15
|
+
GroupKey,
|
|
16
|
+
Leaf,
|
|
17
|
+
Not,
|
|
18
|
+
OffsetRange,
|
|
19
|
+
Or,
|
|
20
|
+
ParseResult,
|
|
21
|
+
Pivot,
|
|
22
|
+
ProtocolIssue,
|
|
23
|
+
ProtocolValidationError,
|
|
24
|
+
RowsRequest,
|
|
25
|
+
Scalar,
|
|
26
|
+
SortItem,
|
|
27
|
+
Tree,
|
|
28
|
+
aggregate_key,
|
|
29
|
+
parse_rows_request,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"AGGREGATE_FNS",
|
|
34
|
+
"FILTER_OPS",
|
|
35
|
+
"GROUP_COUNT_KEY",
|
|
36
|
+
"LIMITS",
|
|
37
|
+
"PROTOCOL_VERSION",
|
|
38
|
+
"TREE_PATH_SEPARATOR",
|
|
39
|
+
"Aggregate",
|
|
40
|
+
"And",
|
|
41
|
+
"CursorRange",
|
|
42
|
+
"FilterNode",
|
|
43
|
+
"Group",
|
|
44
|
+
"GroupKey",
|
|
45
|
+
"Leaf",
|
|
46
|
+
"Not",
|
|
47
|
+
"OffsetRange",
|
|
48
|
+
"Or",
|
|
49
|
+
"ParseResult",
|
|
50
|
+
"Pivot",
|
|
51
|
+
"ProtocolIssue",
|
|
52
|
+
"ProtocolValidationError",
|
|
53
|
+
"RowsRequest",
|
|
54
|
+
"Scalar",
|
|
55
|
+
"SortItem",
|
|
56
|
+
"Tree",
|
|
57
|
+
"aggregate_key",
|
|
58
|
+
"parse_rows_request",
|
|
59
|
+
]
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""The Lattice collab op log server: a port of the `@ember-lattice/server` collab module.
|
|
2
|
+
|
|
3
|
+
The parser and the server import without `wasmtime`. The IronCalc engine is in
|
|
4
|
+
`lattice_grid.collab.ironcalc` and needs the `collab` extra.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from lattice_grid.collab.engine import FormulaEngine
|
|
8
|
+
from lattice_grid.collab.server import Connection, DocServer
|
|
9
|
+
from lattice_grid.collab.store import CollabStore, LogEntry, MemoryStore, Snapshot
|
|
10
|
+
from lattice_grid.collab.wire import (
|
|
11
|
+
COLLAB_LIMITS,
|
|
12
|
+
COLLAB_VERSION,
|
|
13
|
+
Json,
|
|
14
|
+
ParseResult,
|
|
15
|
+
parse_client_message,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"COLLAB_LIMITS",
|
|
20
|
+
"COLLAB_VERSION",
|
|
21
|
+
"CollabStore",
|
|
22
|
+
"Connection",
|
|
23
|
+
"DocServer",
|
|
24
|
+
"FormulaEngine",
|
|
25
|
+
"Json",
|
|
26
|
+
"LogEntry",
|
|
27
|
+
"MemoryStore",
|
|
28
|
+
"ParseResult",
|
|
29
|
+
"Snapshot",
|
|
30
|
+
"parse_client_message",
|
|
31
|
+
]
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""An ASGI WebSocket app for the doc server: a port of socket.ts.
|
|
2
|
+
|
|
3
|
+
It needs no framework. Mount it as a plain ASGI app, for example in Starlette:
|
|
4
|
+
``WebSocketRoute("/collab", CollabWebSocket(server))``. Authenticate the socket before it gets
|
|
5
|
+
here (for example in a middleware): the server trusts the client ID of the join.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import json
|
|
12
|
+
from collections.abc import Awaitable, Callable, MutableMapping
|
|
13
|
+
from typing import Any, NoReturn
|
|
14
|
+
|
|
15
|
+
from lattice_grid.collab.server import DocServer
|
|
16
|
+
from lattice_grid.collab.wire import Json
|
|
17
|
+
|
|
18
|
+
Scope = MutableMapping[str, Any]
|
|
19
|
+
Receive = Callable[[], Awaitable[MutableMapping[str, Any]]]
|
|
20
|
+
SendEvent = Callable[[MutableMapping[str, Any]], Awaitable[None]]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _no_constant(name: str) -> NoReturn:
|
|
24
|
+
# JSON.parse rejects NaN and Infinity; Python accepts them by default.
|
|
25
|
+
raise ValueError(f"{name} is not JSON")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class CollabWebSocket:
|
|
29
|
+
"""Connects each WebSocket to the doc server. Each message is JSON text.
|
|
30
|
+
|
|
31
|
+
A message longer than `max_bytes` characters (default 1 MB, as Node) or one that is not JSON
|
|
32
|
+
gets a reject and is not parsed further.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
def __init__(self, server: DocServer, max_bytes: int = 1_000_000) -> None:
|
|
36
|
+
self.server = server
|
|
37
|
+
self.max_bytes = max_bytes
|
|
38
|
+
|
|
39
|
+
async def __call__(self, scope: Scope, receive: Receive, send: SendEvent) -> None:
|
|
40
|
+
if scope["type"] != "websocket":
|
|
41
|
+
raise ValueError("Lattice: CollabWebSocket serves only the websocket scope")
|
|
42
|
+
if (await receive())["type"] != "websocket.connect":
|
|
43
|
+
return
|
|
44
|
+
await send({"type": "websocket.accept"})
|
|
45
|
+
# The server sends from sync code; one writer keeps the order.
|
|
46
|
+
out: asyncio.Queue[Json] = asyncio.Queue()
|
|
47
|
+
|
|
48
|
+
async def write() -> None:
|
|
49
|
+
while True:
|
|
50
|
+
message = await out.get()
|
|
51
|
+
await send({"type": "websocket.send", "text": json.dumps(message)})
|
|
52
|
+
|
|
53
|
+
writer = asyncio.ensure_future(write())
|
|
54
|
+
conn = self.server.connect(out.put_nowait)
|
|
55
|
+
|
|
56
|
+
def reject(reason: str) -> None:
|
|
57
|
+
out.put_nowait({"v": 1, "type": "reject", "docId": "", "opId": None, "reason": reason})
|
|
58
|
+
|
|
59
|
+
try:
|
|
60
|
+
while True:
|
|
61
|
+
event = await receive()
|
|
62
|
+
if event["type"] == "websocket.disconnect":
|
|
63
|
+
break
|
|
64
|
+
if event["type"] != "websocket.receive":
|
|
65
|
+
continue
|
|
66
|
+
raw = event.get("text")
|
|
67
|
+
if raw is None:
|
|
68
|
+
try:
|
|
69
|
+
raw = bytes(event.get("bytes") or b"").decode("utf-8")
|
|
70
|
+
except UnicodeDecodeError:
|
|
71
|
+
reject("bad_message")
|
|
72
|
+
continue
|
|
73
|
+
if len(raw) > self.max_bytes:
|
|
74
|
+
reject("too_large")
|
|
75
|
+
continue
|
|
76
|
+
try:
|
|
77
|
+
data = json.loads(raw, parse_constant=_no_constant)
|
|
78
|
+
except (ValueError, RecursionError):
|
|
79
|
+
reject("bad_message")
|
|
80
|
+
continue
|
|
81
|
+
conn.receive(data)
|
|
82
|
+
finally:
|
|
83
|
+
conn.close()
|
|
84
|
+
writer.cancel()
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""The formula engine seam of the doc server."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Protocol
|
|
6
|
+
|
|
7
|
+
from lattice_grid.collab.wire import Json
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class FormulaEngine(Protocol):
|
|
11
|
+
"""Computes the cell values of a doc.
|
|
12
|
+
|
|
13
|
+
``load`` takes a ``SheetDoc`` and gives the value of each cell with content.
|
|
14
|
+
``apply`` takes the ops of one submit and gives the computed values that changed
|
|
15
|
+
(``CellChange`` dicts). It raises when it refuses an op; then the server calls ``load``
|
|
16
|
+
again.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def load(self, doc: Json) -> list[Json]: ...
|
|
20
|
+
|
|
21
|
+
def apply(self, ops: list[Json]) -> list[Json]: ...
|