pidgin-codec 0.1.0__tar.gz → 0.2.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.
- pidgin_codec-0.2.0/PKG-INFO +281 -0
- pidgin_codec-0.2.0/README.md +246 -0
- {pidgin_codec-0.1.0 → pidgin_codec-0.2.0}/pyproject.toml +3 -3
- pidgin_codec-0.2.0/src/pidgin/__init__.py +33 -0
- {pidgin_codec-0.1.0 → pidgin_codec-0.2.0}/src/pidgin/contrib/_engine.py +16 -0
- {pidgin_codec-0.1.0 → pidgin_codec-0.2.0}/src/pidgin/contrib/fastapi.py +3 -1
- {pidgin_codec-0.1.0 → pidgin_codec-0.2.0}/src/pidgin/schema_codec.py +202 -24
- pidgin_codec-0.2.0/src/pidgin_codec.egg-info/PKG-INFO +281 -0
- {pidgin_codec-0.1.0 → pidgin_codec-0.2.0}/src/pidgin_codec.egg-info/SOURCES.txt +4 -5
- pidgin_codec-0.2.0/tests/test_encode_safety.py +71 -0
- pidgin_codec-0.2.0/tests/test_js_interop.py +85 -0
- pidgin_codec-0.2.0/tests/test_libpidgin_interop.py +99 -0
- pidgin_codec-0.2.0/tests/test_middleware.py +103 -0
- pidgin_codec-0.2.0/tests/test_schema_codec.py +246 -0
- pidgin_codec-0.1.0/PKG-INFO +0 -297
- pidgin_codec-0.1.0/README.md +0 -262
- pidgin_codec-0.1.0/src/pidgin/__init__.py +0 -47
- pidgin_codec-0.1.0/src/pidgin/_codec.py +0 -132
- pidgin_codec-0.1.0/src/pidgin/_prompts.py +0 -92
- pidgin_codec-0.1.0/src/pidgin/_protocol.py +0 -39
- pidgin_codec-0.1.0/src/pidgin/_types.py +0 -25
- pidgin_codec-0.1.0/src/pidgin_codec.egg-info/PKG-INFO +0 -297
- pidgin_codec-0.1.0/tests/test_protocol.py +0 -35
- pidgin_codec-0.1.0/tests/test_schema_codec.py +0 -86
- {pidgin_codec-0.1.0 → pidgin_codec-0.2.0}/LICENSE +0 -0
- {pidgin_codec-0.1.0 → pidgin_codec-0.2.0}/setup.cfg +0 -0
- {pidgin_codec-0.1.0 → pidgin_codec-0.2.0}/setup.py +0 -0
- {pidgin_codec-0.1.0 → pidgin_codec-0.2.0}/src/pidgin/_fast.c +0 -0
- {pidgin_codec-0.1.0 → pidgin_codec-0.2.0}/src/pidgin/channel.py +0 -0
- {pidgin_codec-0.1.0 → pidgin_codec-0.2.0}/src/pidgin/contrib/__init__.py +0 -0
- {pidgin_codec-0.1.0 → pidgin_codec-0.2.0}/src/pidgin/contrib/django.py +0 -0
- {pidgin_codec-0.1.0 → pidgin_codec-0.2.0}/src/pidgin/py.typed +0 -0
- {pidgin_codec-0.1.0 → pidgin_codec-0.2.0}/src/pidgin/ratchet.py +0 -0
- {pidgin_codec-0.1.0 → pidgin_codec-0.2.0}/src/pidgin_codec.egg-info/dependency_links.txt +0 -0
- {pidgin_codec-0.1.0 → pidgin_codec-0.2.0}/src/pidgin_codec.egg-info/requires.txt +0 -0
- {pidgin_codec-0.1.0 → pidgin_codec-0.2.0}/src/pidgin_codec.egg-info/top_level.txt +0 -0
- {pidgin_codec-0.1.0 → pidgin_codec-0.2.0}/tests/test_channel.py +0 -0
- {pidgin_codec-0.1.0 → pidgin_codec-0.2.0}/tests/test_engine.py +0 -0
- {pidgin_codec-0.1.0 → pidgin_codec-0.2.0}/tests/test_evolution.py +0 -0
- {pidgin_codec-0.1.0 → pidgin_codec-0.2.0}/tests/test_ratchet.py +0 -0
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pidgin-codec
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Runtime-learned binary encoding for JSON APIs: no .proto files, no code generation
|
|
5
|
+
Author: Ivo Gergov
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: compression,json,api,protobuf,binary,schema,codec
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
16
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
17
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: brotli>=1.1.0
|
|
23
|
+
Provides-Extra: crypto
|
|
24
|
+
Requires-Dist: cryptography>=42.0; extra == "crypto"
|
|
25
|
+
Provides-Extra: benchmark
|
|
26
|
+
Requires-Dist: zstandard>=0.23.0; extra == "benchmark"
|
|
27
|
+
Requires-Dist: msgpack>=1.0; extra == "benchmark"
|
|
28
|
+
Requires-Dist: orjson>=3.9; extra == "benchmark"
|
|
29
|
+
Requires-Dist: protobuf>=5.0; extra == "benchmark"
|
|
30
|
+
Requires-Dist: grpcio-tools>=1.60; extra == "benchmark"
|
|
31
|
+
Provides-Extra: dev
|
|
32
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
33
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
|
|
34
|
+
Dynamic: license-file
|
|
35
|
+
|
|
36
|
+
# Pidgin
|
|
37
|
+
|
|
38
|
+
[](LICENSE)
|
|
39
|
+
[](https://python.org)
|
|
40
|
+
|
|
41
|
+
**Runtime-learned binary encoding for JSON APIs.** Pidgin watches your JSON responses, learns their schema, drops the keys and writes the values in a compact binary form. No `.proto` files and no code generation.
|
|
42
|
+
|
|
43
|
+
Status: early. The Python library, the FastAPI and Django middleware and the JavaScript decoder work and are tested. Most web server modules do not work yet. See [What works today](#what-works-today).
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
## How it works
|
|
48
|
+
|
|
49
|
+
1. Pidgin observes JSON responses and learns the schema (field names, types, enum values, nesting).
|
|
50
|
+
2. Keys are dropped (both sides hold the schema) and values are written with type-specific binary encoders.
|
|
51
|
+
3. Brotli runs on top when it makes the payload smaller.
|
|
52
|
+
4. A client asks for it with `Accept-Encoding: pidgin` and decodes with the schema profile the server publishes at `/.well-known/pidgin/<endpoint>`.
|
|
53
|
+
|
|
54
|
+
On generated API data the result is 10.8% to 18.9% of the original JSON, a little smaller than brotli and Protobuf+zstd. On real public API responses it is about the same as brotli. Pidgin is slower to compress than brotli. Numbers and commands are in [Benchmarks](#benchmarks).
|
|
55
|
+
|
|
56
|
+
## What works today
|
|
57
|
+
|
|
58
|
+
Checked for release 0.2.0 by running each piece, not by reading the code. The logs of that check are summarised in [CHANGELOG.md](CHANGELOG.md).
|
|
59
|
+
|
|
60
|
+
| Integration | State | What was checked |
|
|
61
|
+
|---|---|---|
|
|
62
|
+
| Python library (`SchemaCodec`) | Works, tested | unit tests, C extension and pure Python encoders |
|
|
63
|
+
| `RatchetCipher`, `SecureChannel` | Works, tested | unit tests (needs the `crypto` extra) |
|
|
64
|
+
| FastAPI middleware | Works, tested | real uvicorn server, `Accept-Encoding: pidgin`, body decodes to the same JSON |
|
|
65
|
+
| Django middleware | Works, tested | real Django server, same check |
|
|
66
|
+
| JavaScript decoder (`PidginDecoder`) | Works, tested | decodes Python and libpidgin output to the same data |
|
|
67
|
+
| C library (`libpidgin`) | Works, tested | C tests, output decoded by Python and JavaScript |
|
|
68
|
+
| Kong plugin | Experimental | header parsing unit test passes and the engine it wraps is tested; the plugin was not run inside Kong for this release |
|
|
69
|
+
| JavaScript `PidginClient` | Not working yet | sends `Accept: application/x-pidgin`, which no Pidgin server reads, so it always gets plain JSON. Browsers do not let scripts set `Accept-Encoding` |
|
|
70
|
+
| nginx module | Not working yet | loads and learns, but never compresses a response |
|
|
71
|
+
| Apache module | Not working yet | builds, never run against Apache |
|
|
72
|
+
| Caddy module | Not working yet | the Caddy build cannot find the module |
|
|
73
|
+
| Traefik plugin | Not working yet | Go code builds, Traefik cannot load the plugin |
|
|
74
|
+
| HAProxy agent | Not working yet | agent builds, the HAProxy config uses an action HAProxy does not have |
|
|
75
|
+
|
|
76
|
+
Known limits of the working parts:
|
|
77
|
+
|
|
78
|
+
- `compress()` checks its own output. Data that does not fit the learned profile (a required field missing, an integer wider than 64 bits, a list where a string was learned) raises `PidginEncodeError` instead of producing a payload that decodes to something else. The middleware then sends plain JSON. `compress(data, verify=False)` skips the check.
|
|
79
|
+
- Responses wrapped for pagination, such as `{"data": [...], "total": 10}`, are sent as plain JSON. Only a record or a list of records is encoded. A record that has a list field named `data`, `results`, `items` or `records` is taken for such a wrapper and is also sent as JSON.
|
|
80
|
+
- A payload decodes only with the profile it was encoded with. When the server's profile changes (it evolves after schema drift), clients must fetch the new one. The middleware sends the current profile ETag in `X-Pidgin-ETag`.
|
|
81
|
+
- Decoded objects come back with keys in schema order, not in the order the server wrote them. Values are identical.
|
|
82
|
+
|
|
83
|
+
## Quick start
|
|
84
|
+
|
|
85
|
+
### Python library
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
pip install pidgin-codec
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
The PyPI package is a source distribution, so installing it builds a small C extension (a C compiler is needed).
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
from pidgin import SchemaCodec
|
|
95
|
+
|
|
96
|
+
codec = SchemaCodec.learn(sample_records) # learn from 20-50 records
|
|
97
|
+
compressed = codec.compress(records) # dict or list[dict] -> bytes
|
|
98
|
+
original = codec.decompress(compressed) # same data back
|
|
99
|
+
profile_json = codec.profile.to_json() # give this to clients
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### FastAPI
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
from fastapi import FastAPI
|
|
106
|
+
from pidgin.contrib.fastapi import PidginMiddleware
|
|
107
|
+
|
|
108
|
+
app = FastAPI()
|
|
109
|
+
app.add_middleware(PidginMiddleware)
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### Django
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
# settings.py
|
|
116
|
+
MIDDLEWARE = [
|
|
117
|
+
"pidgin.contrib.django.PidginMiddleware",
|
|
118
|
+
# ...
|
|
119
|
+
]
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
The middleware learns from the first 30 records it sees per endpoint, then encodes responses for clients that send `Accept-Encoding: pidgin`. Other clients keep getting JSON. Profiles are served at `/.well-known/pidgin/<endpoint>`, for example `/.well-known/pidgin/api-users` for `/api/users`.
|
|
123
|
+
|
|
124
|
+
### JavaScript decoder
|
|
125
|
+
|
|
126
|
+
```bash
|
|
127
|
+
npm install @pidgin/codec
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
```typescript
|
|
131
|
+
import { PidginDecoder } from "@pidgin/codec";
|
|
132
|
+
import { brotliDecompressSync } from "node:zlib";
|
|
133
|
+
|
|
134
|
+
// profile: JSON text from /.well-known/pidgin/<endpoint>
|
|
135
|
+
// body: the response bytes (Content-Encoding: pidgin)
|
|
136
|
+
const decoder = PidginDecoder.fromJSON(profile, (b) => new Uint8Array(brotliDecompressSync(b)));
|
|
137
|
+
const data = await decoder.decode(body);
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
Pass a brotli function. Without one the decoder falls back to `DecompressionStream("br")`, which Node 22 does not have; brotli payloads then fail with a clear error.
|
|
141
|
+
|
|
142
|
+
## Benchmarks
|
|
143
|
+
|
|
144
|
+
Measured on 24 November 2026: Apple M5 Max laptop, Python 3.15, C extension on, single thread. Lower is better.
|
|
145
|
+
|
|
146
|
+
### Generated API data
|
|
147
|
+
|
|
148
|
+
`python benchmarks/realistic_api.py`
|
|
149
|
+
|
|
150
|
+
| Dataset | gzip -6 | brotli -6 | Protobuf+zstd | Pidgin |
|
|
151
|
+
|---|---|---|---|---|
|
|
152
|
+
| Users x1000 | 21.4% | 19.5% | 20.3% | 18.9% |
|
|
153
|
+
| Orders x500 (nested) | 19.1% | 17.5% | 17.4% | 16.1% |
|
|
154
|
+
| Events x5000 | 13.6% | 12.3% | 12.3% | 10.8% |
|
|
155
|
+
|
|
156
|
+
Time to compress, in ms, with the default output check:
|
|
157
|
+
|
|
158
|
+
| Dataset | brotli -6 | zstd -6 | Protobuf+zstd | Pidgin |
|
|
159
|
+
|---|---|---|---|---|
|
|
160
|
+
| Users x1000 | 11.1 | 7.0 | 8.2 | 30.7 |
|
|
161
|
+
| Orders x500 | 10.8 | 5.8 | 8.0 | 34.3 |
|
|
162
|
+
| Events x5000 | 35.8 | 19.9 | 21.1 | 86.8 |
|
|
163
|
+
|
|
164
|
+
Pidgin is smaller on this data and 2.5 to 3 times slower to compress than brotli. Without the output check (`verify=False`) the same run measured 16.7, 20.7 and 63.3 ms. Times vary between runs on a laptop; sizes do not.
|
|
165
|
+
|
|
166
|
+
### Real public API responses
|
|
167
|
+
|
|
168
|
+
`python benchmarks/extended_real_api.py` (16 cached responses in `benchmarks/real_api_fixtures`, checksums verified)
|
|
169
|
+
|
|
170
|
+
| API | Fields | brotli | Pidgin |
|
|
171
|
+
|---|---|---|---|
|
|
172
|
+
| GitHub Repos | 46 | 6.7% | 6.0% |
|
|
173
|
+
| GitHub Repo Search | 82 | 8.8% | 8.4% |
|
|
174
|
+
| Rick and Morty Characters | 12 | 6.0% | 4.6% |
|
|
175
|
+
| JSONPlaceholder Posts | 4 | 27.5% | 27.5% |
|
|
176
|
+
| JSONPlaceholder Comments | 5 | 27.5% | 28.4% |
|
|
177
|
+
| JSONPlaceholder Photos | 5 | 13.5% | 14.3% |
|
|
178
|
+
| CoinGecko Top Coins | 26 | 22.9% | 23.9% |
|
|
179
|
+
|
|
180
|
+
Across all 16: Pidgin is smaller on 5, equal on 3 and larger on 8. Median 18.3% for Pidgin, 18.0% for brotli. Pidgin helps most on responses with many fields and nested objects, and does not help on text-heavy or few-field data. Every response decoded back to the same data.
|
|
181
|
+
|
|
182
|
+
## Schema evolution
|
|
183
|
+
|
|
184
|
+
```python
|
|
185
|
+
v2_profile = codec.profile.evolve(new_samples)
|
|
186
|
+
v2_codec = SchemaCodec(v2_profile)
|
|
187
|
+
|
|
188
|
+
for line in codec.profile.diff(v2_profile):
|
|
189
|
+
print(line)
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
| Change | What happens |
|
|
193
|
+
|--------|-------------|
|
|
194
|
+
| New field added | Written as JSON inside the payload until the profile evolves, then typed |
|
|
195
|
+
| Field becomes optional | Evolved profile marks it nullable; absent costs one byte |
|
|
196
|
+
| New enum value | Appended, old indices keep their meaning |
|
|
197
|
+
| Int becomes float | Widened |
|
|
198
|
+
| Schema drift in the middleware | Every 500 requests the keys are compared; if they changed the profile evolves and its version and ETag change |
|
|
199
|
+
|
|
200
|
+
An evolved codec reads both old and new shapes of the data. A payload encoded with one profile version cannot be decoded with another version, so clients must refresh the profile when the ETag changes.
|
|
201
|
+
|
|
202
|
+
## Optional: encryption
|
|
203
|
+
|
|
204
|
+
```bash
|
|
205
|
+
pip install "pidgin-codec[crypto]"
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
```python
|
|
209
|
+
from pidgin import RatchetCipher
|
|
210
|
+
|
|
211
|
+
cipher = RatchetCipher(shared_secret=b"key")
|
|
212
|
+
encrypted = cipher.encrypt(compressed) # key moves forward after each message
|
|
213
|
+
original = peer_cipher.decrypt(encrypted) # peer with the same secret stays in step
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
```python
|
|
217
|
+
from pidgin import SecureChannel
|
|
218
|
+
|
|
219
|
+
alice = SecureChannel.create("alice")
|
|
220
|
+
bob = SecureChannel.create("bob")
|
|
221
|
+
alice.handshake(bob.public_key) # X25519 key exchange
|
|
222
|
+
bob.handshake(alice.public_key)
|
|
223
|
+
envelope = alice.send("Hello") # compress, encrypt, sign
|
|
224
|
+
message = bob.receive(envelope) # dict with text, sender, id, ts
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
## C library
|
|
228
|
+
|
|
229
|
+
`libpidgin` is the engine the server modules are built on.
|
|
230
|
+
|
|
231
|
+
```c
|
|
232
|
+
#include <pidgin.h>
|
|
233
|
+
|
|
234
|
+
pidgin_engine_t *engine = pidgin_engine_create(30, 500);
|
|
235
|
+
pidgin_engine_observe(engine, "/api/users", json_str);
|
|
236
|
+
|
|
237
|
+
if (pidgin_engine_ready(engine, "/api/users")) {
|
|
238
|
+
pidgin_buf_t compressed = pidgin_engine_compress(engine, "/api/users", json_str);
|
|
239
|
+
if (compressed.len > 0) {
|
|
240
|
+
/* send compressed.data (compressed.len bytes) */
|
|
241
|
+
} else {
|
|
242
|
+
/* data does not fit the profile: send json_str as it is */
|
|
243
|
+
}
|
|
244
|
+
pidgin_buf_free(&compressed);
|
|
245
|
+
}
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
Build and test: `make -C libpidgin && make -C libpidgin test` (needs brotli).
|
|
249
|
+
|
|
250
|
+
## Running the checks
|
|
251
|
+
|
|
252
|
+
```bash
|
|
253
|
+
make setup # venv with the C extension
|
|
254
|
+
.venv/bin/pip install fastapi httpx django # for the middleware tests
|
|
255
|
+
make -C libpidgin # enables the C and Python tests against libpidgin
|
|
256
|
+
cd clients/js && npm ci && npm test && cd ../.. # JS decoder; also enables the Python to JS test
|
|
257
|
+
make test
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
Tests whose tools are missing are skipped, not failed.
|
|
261
|
+
|
|
262
|
+
## Project structure
|
|
263
|
+
|
|
264
|
+
```
|
|
265
|
+
pidgin/
|
|
266
|
+
src/pidgin/ Python package with C extension and FastAPI/Django middleware
|
|
267
|
+
libpidgin/ C library
|
|
268
|
+
clients/js/ TypeScript decoder (@pidgin/codec)
|
|
269
|
+
modules/ Kong (experimental); nginx, Apache, Caddy, Traefik, HAProxy (not working yet)
|
|
270
|
+
benchmarks/ comparison scripts and fixtures
|
|
271
|
+
docker/ test stack for the server modules
|
|
272
|
+
docs/ landing page
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
## License
|
|
276
|
+
|
|
277
|
+
MIT, see [LICENSE](LICENSE).
|
|
278
|
+
|
|
279
|
+
---
|
|
280
|
+
|
|
281
|
+
Built by Evo Tech Labs.
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
# Pidgin
|
|
2
|
+
|
|
3
|
+
[](LICENSE)
|
|
4
|
+
[](https://python.org)
|
|
5
|
+
|
|
6
|
+
**Runtime-learned binary encoding for JSON APIs.** Pidgin watches your JSON responses, learns their schema, drops the keys and writes the values in a compact binary form. No `.proto` files and no code generation.
|
|
7
|
+
|
|
8
|
+
Status: early. The Python library, the FastAPI and Django middleware and the JavaScript decoder work and are tested. Most web server modules do not work yet. See [What works today](#what-works-today).
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## How it works
|
|
13
|
+
|
|
14
|
+
1. Pidgin observes JSON responses and learns the schema (field names, types, enum values, nesting).
|
|
15
|
+
2. Keys are dropped (both sides hold the schema) and values are written with type-specific binary encoders.
|
|
16
|
+
3. Brotli runs on top when it makes the payload smaller.
|
|
17
|
+
4. A client asks for it with `Accept-Encoding: pidgin` and decodes with the schema profile the server publishes at `/.well-known/pidgin/<endpoint>`.
|
|
18
|
+
|
|
19
|
+
On generated API data the result is 10.8% to 18.9% of the original JSON, a little smaller than brotli and Protobuf+zstd. On real public API responses it is about the same as brotli. Pidgin is slower to compress than brotli. Numbers and commands are in [Benchmarks](#benchmarks).
|
|
20
|
+
|
|
21
|
+
## What works today
|
|
22
|
+
|
|
23
|
+
Checked for release 0.2.0 by running each piece, not by reading the code. The logs of that check are summarised in [CHANGELOG.md](CHANGELOG.md).
|
|
24
|
+
|
|
25
|
+
| Integration | State | What was checked |
|
|
26
|
+
|---|---|---|
|
|
27
|
+
| Python library (`SchemaCodec`) | Works, tested | unit tests, C extension and pure Python encoders |
|
|
28
|
+
| `RatchetCipher`, `SecureChannel` | Works, tested | unit tests (needs the `crypto` extra) |
|
|
29
|
+
| FastAPI middleware | Works, tested | real uvicorn server, `Accept-Encoding: pidgin`, body decodes to the same JSON |
|
|
30
|
+
| Django middleware | Works, tested | real Django server, same check |
|
|
31
|
+
| JavaScript decoder (`PidginDecoder`) | Works, tested | decodes Python and libpidgin output to the same data |
|
|
32
|
+
| C library (`libpidgin`) | Works, tested | C tests, output decoded by Python and JavaScript |
|
|
33
|
+
| Kong plugin | Experimental | header parsing unit test passes and the engine it wraps is tested; the plugin was not run inside Kong for this release |
|
|
34
|
+
| JavaScript `PidginClient` | Not working yet | sends `Accept: application/x-pidgin`, which no Pidgin server reads, so it always gets plain JSON. Browsers do not let scripts set `Accept-Encoding` |
|
|
35
|
+
| nginx module | Not working yet | loads and learns, but never compresses a response |
|
|
36
|
+
| Apache module | Not working yet | builds, never run against Apache |
|
|
37
|
+
| Caddy module | Not working yet | the Caddy build cannot find the module |
|
|
38
|
+
| Traefik plugin | Not working yet | Go code builds, Traefik cannot load the plugin |
|
|
39
|
+
| HAProxy agent | Not working yet | agent builds, the HAProxy config uses an action HAProxy does not have |
|
|
40
|
+
|
|
41
|
+
Known limits of the working parts:
|
|
42
|
+
|
|
43
|
+
- `compress()` checks its own output. Data that does not fit the learned profile (a required field missing, an integer wider than 64 bits, a list where a string was learned) raises `PidginEncodeError` instead of producing a payload that decodes to something else. The middleware then sends plain JSON. `compress(data, verify=False)` skips the check.
|
|
44
|
+
- Responses wrapped for pagination, such as `{"data": [...], "total": 10}`, are sent as plain JSON. Only a record or a list of records is encoded. A record that has a list field named `data`, `results`, `items` or `records` is taken for such a wrapper and is also sent as JSON.
|
|
45
|
+
- A payload decodes only with the profile it was encoded with. When the server's profile changes (it evolves after schema drift), clients must fetch the new one. The middleware sends the current profile ETag in `X-Pidgin-ETag`.
|
|
46
|
+
- Decoded objects come back with keys in schema order, not in the order the server wrote them. Values are identical.
|
|
47
|
+
|
|
48
|
+
## Quick start
|
|
49
|
+
|
|
50
|
+
### Python library
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
pip install pidgin-codec
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
The PyPI package is a source distribution, so installing it builds a small C extension (a C compiler is needed).
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
from pidgin import SchemaCodec
|
|
60
|
+
|
|
61
|
+
codec = SchemaCodec.learn(sample_records) # learn from 20-50 records
|
|
62
|
+
compressed = codec.compress(records) # dict or list[dict] -> bytes
|
|
63
|
+
original = codec.decompress(compressed) # same data back
|
|
64
|
+
profile_json = codec.profile.to_json() # give this to clients
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### FastAPI
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
from fastapi import FastAPI
|
|
71
|
+
from pidgin.contrib.fastapi import PidginMiddleware
|
|
72
|
+
|
|
73
|
+
app = FastAPI()
|
|
74
|
+
app.add_middleware(PidginMiddleware)
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
### Django
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
# settings.py
|
|
81
|
+
MIDDLEWARE = [
|
|
82
|
+
"pidgin.contrib.django.PidginMiddleware",
|
|
83
|
+
# ...
|
|
84
|
+
]
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
The middleware learns from the first 30 records it sees per endpoint, then encodes responses for clients that send `Accept-Encoding: pidgin`. Other clients keep getting JSON. Profiles are served at `/.well-known/pidgin/<endpoint>`, for example `/.well-known/pidgin/api-users` for `/api/users`.
|
|
88
|
+
|
|
89
|
+
### JavaScript decoder
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
npm install @pidgin/codec
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
```typescript
|
|
96
|
+
import { PidginDecoder } from "@pidgin/codec";
|
|
97
|
+
import { brotliDecompressSync } from "node:zlib";
|
|
98
|
+
|
|
99
|
+
// profile: JSON text from /.well-known/pidgin/<endpoint>
|
|
100
|
+
// body: the response bytes (Content-Encoding: pidgin)
|
|
101
|
+
const decoder = PidginDecoder.fromJSON(profile, (b) => new Uint8Array(brotliDecompressSync(b)));
|
|
102
|
+
const data = await decoder.decode(body);
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Pass a brotli function. Without one the decoder falls back to `DecompressionStream("br")`, which Node 22 does not have; brotli payloads then fail with a clear error.
|
|
106
|
+
|
|
107
|
+
## Benchmarks
|
|
108
|
+
|
|
109
|
+
Measured on 24 November 2026: Apple M5 Max laptop, Python 3.15, C extension on, single thread. Lower is better.
|
|
110
|
+
|
|
111
|
+
### Generated API data
|
|
112
|
+
|
|
113
|
+
`python benchmarks/realistic_api.py`
|
|
114
|
+
|
|
115
|
+
| Dataset | gzip -6 | brotli -6 | Protobuf+zstd | Pidgin |
|
|
116
|
+
|---|---|---|---|---|
|
|
117
|
+
| Users x1000 | 21.4% | 19.5% | 20.3% | 18.9% |
|
|
118
|
+
| Orders x500 (nested) | 19.1% | 17.5% | 17.4% | 16.1% |
|
|
119
|
+
| Events x5000 | 13.6% | 12.3% | 12.3% | 10.8% |
|
|
120
|
+
|
|
121
|
+
Time to compress, in ms, with the default output check:
|
|
122
|
+
|
|
123
|
+
| Dataset | brotli -6 | zstd -6 | Protobuf+zstd | Pidgin |
|
|
124
|
+
|---|---|---|---|---|
|
|
125
|
+
| Users x1000 | 11.1 | 7.0 | 8.2 | 30.7 |
|
|
126
|
+
| Orders x500 | 10.8 | 5.8 | 8.0 | 34.3 |
|
|
127
|
+
| Events x5000 | 35.8 | 19.9 | 21.1 | 86.8 |
|
|
128
|
+
|
|
129
|
+
Pidgin is smaller on this data and 2.5 to 3 times slower to compress than brotli. Without the output check (`verify=False`) the same run measured 16.7, 20.7 and 63.3 ms. Times vary between runs on a laptop; sizes do not.
|
|
130
|
+
|
|
131
|
+
### Real public API responses
|
|
132
|
+
|
|
133
|
+
`python benchmarks/extended_real_api.py` (16 cached responses in `benchmarks/real_api_fixtures`, checksums verified)
|
|
134
|
+
|
|
135
|
+
| API | Fields | brotli | Pidgin |
|
|
136
|
+
|---|---|---|---|
|
|
137
|
+
| GitHub Repos | 46 | 6.7% | 6.0% |
|
|
138
|
+
| GitHub Repo Search | 82 | 8.8% | 8.4% |
|
|
139
|
+
| Rick and Morty Characters | 12 | 6.0% | 4.6% |
|
|
140
|
+
| JSONPlaceholder Posts | 4 | 27.5% | 27.5% |
|
|
141
|
+
| JSONPlaceholder Comments | 5 | 27.5% | 28.4% |
|
|
142
|
+
| JSONPlaceholder Photos | 5 | 13.5% | 14.3% |
|
|
143
|
+
| CoinGecko Top Coins | 26 | 22.9% | 23.9% |
|
|
144
|
+
|
|
145
|
+
Across all 16: Pidgin is smaller on 5, equal on 3 and larger on 8. Median 18.3% for Pidgin, 18.0% for brotli. Pidgin helps most on responses with many fields and nested objects, and does not help on text-heavy or few-field data. Every response decoded back to the same data.
|
|
146
|
+
|
|
147
|
+
## Schema evolution
|
|
148
|
+
|
|
149
|
+
```python
|
|
150
|
+
v2_profile = codec.profile.evolve(new_samples)
|
|
151
|
+
v2_codec = SchemaCodec(v2_profile)
|
|
152
|
+
|
|
153
|
+
for line in codec.profile.diff(v2_profile):
|
|
154
|
+
print(line)
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
| Change | What happens |
|
|
158
|
+
|--------|-------------|
|
|
159
|
+
| New field added | Written as JSON inside the payload until the profile evolves, then typed |
|
|
160
|
+
| Field becomes optional | Evolved profile marks it nullable; absent costs one byte |
|
|
161
|
+
| New enum value | Appended, old indices keep their meaning |
|
|
162
|
+
| Int becomes float | Widened |
|
|
163
|
+
| Schema drift in the middleware | Every 500 requests the keys are compared; if they changed the profile evolves and its version and ETag change |
|
|
164
|
+
|
|
165
|
+
An evolved codec reads both old and new shapes of the data. A payload encoded with one profile version cannot be decoded with another version, so clients must refresh the profile when the ETag changes.
|
|
166
|
+
|
|
167
|
+
## Optional: encryption
|
|
168
|
+
|
|
169
|
+
```bash
|
|
170
|
+
pip install "pidgin-codec[crypto]"
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
```python
|
|
174
|
+
from pidgin import RatchetCipher
|
|
175
|
+
|
|
176
|
+
cipher = RatchetCipher(shared_secret=b"key")
|
|
177
|
+
encrypted = cipher.encrypt(compressed) # key moves forward after each message
|
|
178
|
+
original = peer_cipher.decrypt(encrypted) # peer with the same secret stays in step
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
```python
|
|
182
|
+
from pidgin import SecureChannel
|
|
183
|
+
|
|
184
|
+
alice = SecureChannel.create("alice")
|
|
185
|
+
bob = SecureChannel.create("bob")
|
|
186
|
+
alice.handshake(bob.public_key) # X25519 key exchange
|
|
187
|
+
bob.handshake(alice.public_key)
|
|
188
|
+
envelope = alice.send("Hello") # compress, encrypt, sign
|
|
189
|
+
message = bob.receive(envelope) # dict with text, sender, id, ts
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
## C library
|
|
193
|
+
|
|
194
|
+
`libpidgin` is the engine the server modules are built on.
|
|
195
|
+
|
|
196
|
+
```c
|
|
197
|
+
#include <pidgin.h>
|
|
198
|
+
|
|
199
|
+
pidgin_engine_t *engine = pidgin_engine_create(30, 500);
|
|
200
|
+
pidgin_engine_observe(engine, "/api/users", json_str);
|
|
201
|
+
|
|
202
|
+
if (pidgin_engine_ready(engine, "/api/users")) {
|
|
203
|
+
pidgin_buf_t compressed = pidgin_engine_compress(engine, "/api/users", json_str);
|
|
204
|
+
if (compressed.len > 0) {
|
|
205
|
+
/* send compressed.data (compressed.len bytes) */
|
|
206
|
+
} else {
|
|
207
|
+
/* data does not fit the profile: send json_str as it is */
|
|
208
|
+
}
|
|
209
|
+
pidgin_buf_free(&compressed);
|
|
210
|
+
}
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
Build and test: `make -C libpidgin && make -C libpidgin test` (needs brotli).
|
|
214
|
+
|
|
215
|
+
## Running the checks
|
|
216
|
+
|
|
217
|
+
```bash
|
|
218
|
+
make setup # venv with the C extension
|
|
219
|
+
.venv/bin/pip install fastapi httpx django # for the middleware tests
|
|
220
|
+
make -C libpidgin # enables the C and Python tests against libpidgin
|
|
221
|
+
cd clients/js && npm ci && npm test && cd ../.. # JS decoder; also enables the Python to JS test
|
|
222
|
+
make test
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
Tests whose tools are missing are skipped, not failed.
|
|
226
|
+
|
|
227
|
+
## Project structure
|
|
228
|
+
|
|
229
|
+
```
|
|
230
|
+
pidgin/
|
|
231
|
+
src/pidgin/ Python package with C extension and FastAPI/Django middleware
|
|
232
|
+
libpidgin/ C library
|
|
233
|
+
clients/js/ TypeScript decoder (@pidgin/codec)
|
|
234
|
+
modules/ Kong (experimental); nginx, Apache, Caddy, Traefik, HAProxy (not working yet)
|
|
235
|
+
benchmarks/ comparison scripts and fixtures
|
|
236
|
+
docker/ test stack for the server modules
|
|
237
|
+
docs/ landing page
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
## License
|
|
241
|
+
|
|
242
|
+
MIT, see [LICENSE](LICENSE).
|
|
243
|
+
|
|
244
|
+
---
|
|
245
|
+
|
|
246
|
+
Built by Evo Tech Labs.
|
|
@@ -4,8 +4,8 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "pidgin-codec"
|
|
7
|
-
version = "0.
|
|
8
|
-
description = "Runtime-learned
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "Runtime-learned binary encoding for JSON APIs: no .proto files, no code generation"
|
|
9
9
|
requires-python = ">=3.10"
|
|
10
10
|
license = "MIT"
|
|
11
11
|
readme = "README.md"
|
|
@@ -13,7 +13,7 @@ authors = [
|
|
|
13
13
|
{name = "Ivo Gergov"},
|
|
14
14
|
]
|
|
15
15
|
classifiers = [
|
|
16
|
-
"Development Status ::
|
|
16
|
+
"Development Status :: 3 - Alpha",
|
|
17
17
|
"Intended Audience :: Developers",
|
|
18
18
|
|
|
19
19
|
"Programming Language :: Python :: 3",
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Pidgin: runtime-learned compression for JSON APIs.
|
|
2
|
+
|
|
3
|
+
Schema-aware API compression:
|
|
4
|
+
from pidgin import SchemaCodec
|
|
5
|
+
codec = SchemaCodec.learn(sample_responses)
|
|
6
|
+
compressed = codec.compress(response)
|
|
7
|
+
original = codec.decompress(compressed)
|
|
8
|
+
|
|
9
|
+
Ratchet cipher (needs the crypto extra):
|
|
10
|
+
from pidgin import RatchetCipher
|
|
11
|
+
cipher = RatchetCipher(shared_secret=b"key")
|
|
12
|
+
encrypted = cipher.encrypt(data)
|
|
13
|
+
|
|
14
|
+
Secure channel (needs the crypto extra):
|
|
15
|
+
from pidgin import SecureChannel
|
|
16
|
+
channel = SecureChannel.create("alice")
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from pidgin.ratchet import RatchetCipher
|
|
20
|
+
from pidgin.schema_codec import PidginDecodeError, PidginEncodeError, SchemaCodec
|
|
21
|
+
|
|
22
|
+
__version__ = "0.2.0"
|
|
23
|
+
__all__ = [
|
|
24
|
+
"SchemaCodec", "PidginEncodeError", "PidginDecodeError",
|
|
25
|
+
"RatchetCipher", "SecureChannel",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def __getattr__(name: str):
|
|
30
|
+
if name == "SecureChannel":
|
|
31
|
+
from pidgin.channel import SecureChannel
|
|
32
|
+
return SecureChannel
|
|
33
|
+
raise AttributeError(f"module 'pidgin' has no attribute {name!r}")
|
|
@@ -104,6 +104,13 @@ class PidginEngine:
|
|
|
104
104
|
if state.codec is None:
|
|
105
105
|
return None
|
|
106
106
|
|
|
107
|
+
# The profile is learned from the records inside the response. A
|
|
108
|
+
# pagination wrapper such as {"data": [...], "total": 10} has a
|
|
109
|
+
# different shape, so encoding it with that profile would decode to
|
|
110
|
+
# the wrong object. Send those responses as plain JSON instead.
|
|
111
|
+
if not self._is_bare_records(data):
|
|
112
|
+
return None
|
|
113
|
+
|
|
107
114
|
try:
|
|
108
115
|
return state.codec.compress(data)
|
|
109
116
|
except Exception:
|
|
@@ -171,6 +178,15 @@ class PidginEngine:
|
|
|
171
178
|
return [data]
|
|
172
179
|
return []
|
|
173
180
|
|
|
181
|
+
@classmethod
|
|
182
|
+
def _is_bare_records(cls, data: Any) -> bool:
|
|
183
|
+
"""True when data is a record or a list of records, not a wrapper."""
|
|
184
|
+
if isinstance(data, list):
|
|
185
|
+
return bool(data) and all(isinstance(r, dict) for r in data)
|
|
186
|
+
if isinstance(data, dict):
|
|
187
|
+
return cls._extract_records(data) == [data]
|
|
188
|
+
return False
|
|
189
|
+
|
|
174
190
|
@staticmethod
|
|
175
191
|
def _hash_keys(records: list[dict]) -> str:
|
|
176
192
|
"""Hash the key structure of records for drift detection."""
|
|
@@ -138,7 +138,9 @@ class PidginMiddleware(BaseHTTPMiddleware):
|
|
|
138
138
|
)
|
|
139
139
|
|
|
140
140
|
# Return compressed response
|
|
141
|
-
|
|
141
|
+
# Drop the length of the original JSON body; Response sets the
|
|
142
|
+
# correct one for the compressed body.
|
|
143
|
+
headers = {k: v for k, v in response.headers.items() if k.lower() != "content-length"}
|
|
142
144
|
headers["content-encoding"] = "pidgin"
|
|
143
145
|
headers["content-type"] = "application/octet-stream"
|
|
144
146
|
headers["x-pidgin-profile"] = self.engine.get_profile_endpoint(endpoint)
|