streamcast 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.
- streamcast-0.1.0/LICENSE +202 -0
- streamcast-0.1.0/NOTICE +4 -0
- streamcast-0.1.0/PKG-INFO +399 -0
- streamcast-0.1.0/README.md +376 -0
- streamcast-0.1.0/pyproject.toml +97 -0
- streamcast-0.1.0/pyproject.toml.orig +138 -0
- streamcast-0.1.0/src/streamcast/__init__.py +128 -0
- streamcast-0.1.0/src/streamcast/__main__.py +42 -0
- streamcast-0.1.0/src/streamcast/_catchup.py +448 -0
- streamcast-0.1.0/src/streamcast/_client.py +772 -0
- streamcast-0.1.0/src/streamcast/_cursor.py +153 -0
- streamcast-0.1.0/src/streamcast/_errors.py +202 -0
- streamcast-0.1.0/src/streamcast/_log.py +217 -0
- streamcast-0.1.0/src/streamcast/_maintain.py +274 -0
- streamcast-0.1.0/src/streamcast/_protocol.py +417 -0
- streamcast-0.1.0/src/streamcast/_remote.py +198 -0
- streamcast-0.1.0/src/streamcast/_replicate.py +253 -0
- streamcast-0.1.0/src/streamcast/_schema.py +262 -0
- streamcast-0.1.0/src/streamcast/_server.py +318 -0
- streamcast-0.1.0/src/streamcast/_stream.py +686 -0
- streamcast-0.1.0/src/streamcast/_subscriber.py +168 -0
- streamcast-0.1.0/src/streamcast/py.typed +0 -0
streamcast-0.1.0/LICENSE
ADDED
|
@@ -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.
|
streamcast-0.1.0/NOTICE
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: streamcast
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A replayable WebSocket multicaster. One stream in, logged to an Iceberg table, broadcast to many.
|
|
5
|
+
Keywords: websocket,multicast,broadcast,tickerplant,market-data
|
|
6
|
+
Author: Nico Bautista Hobin
|
|
7
|
+
Author-email: Nico Bautista Hobin <nico@penca.io>
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
License-File: NOTICE
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Framework :: AsyncIO
|
|
13
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
14
|
+
Classifier: Topic :: System :: Networking
|
|
15
|
+
Classifier: Typing :: Typed
|
|
16
|
+
Requires-Dist: websockets>=14
|
|
17
|
+
Requires-Dist: litelink>=0.4.0
|
|
18
|
+
Requires-Dist: msgspec>=0.18
|
|
19
|
+
Requires-Python: >=3.11, <3.14
|
|
20
|
+
Project-URL: Source, https://github.com/nhobin219/streamcast
|
|
21
|
+
Project-URL: Specification, https://github.com/nhobin219/streamcast/blob/main/docs/SPEC.md
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# streamcast
|
|
25
|
+
|
|
26
|
+
A replayable WebSocket multicaster. One upstream stream in, appended to a
|
|
27
|
+
[litelink](https://github.com/nhobin219/litelink) log — an Iceberg table on disk — and
|
|
28
|
+
broadcast to any number of downstream subscribers. Each message carries the offset it was
|
|
29
|
+
written at, so a subscriber that stops can reconnect and ask for the rest.
|
|
30
|
+
|
|
31
|
+
[](LICENSE)
|
|
32
|
+
[](pyproject.toml)
|
|
33
|
+
|
|
34
|
+
```
|
|
35
|
+
upstream ws feed
|
|
36
|
+
│ one connection
|
|
37
|
+
▼
|
|
38
|
+
streamcast server ──► litelink log durable BEFORE any subscriber sees it
|
|
39
|
+
│ fan-out
|
|
40
|
+
├──► strategy offset 1861
|
|
41
|
+
├──► dashboard offset 1861
|
|
42
|
+
└──► recorder offset 1861
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Every subscriber receives the same bytes in the same order, from one `encode` call.
|
|
46
|
+
The API is `websockets` with two deliberate differences, listed below.
|
|
47
|
+
|
|
48
|
+
A streamcast server is a Python WebSocket
|
|
49
|
+
[tickerplant](https://code.kx.com/q/architecture/): a process that captures a feed,
|
|
50
|
+
optionally writes it to a log, and publishes it to registered subscribers.
|
|
51
|
+
|
|
52
|
+
**Status: early.** 0.1.0 is the first release. Read [what it is not](#what-it-is-not)
|
|
53
|
+
and [not implemented yet](#not-implemented-yet) first.
|
|
54
|
+
|
|
55
|
+
## Install
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
uv add streamcast
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## API
|
|
62
|
+
|
|
63
|
+
**It is the `websockets` API.** `serve` and `connect` have the same shapes and pass every
|
|
64
|
+
keyword through, so `ssl`, `ping_interval`, `process_request`, `max_queue` and the rest
|
|
65
|
+
behave exactly as they do there, and `serve` returns an object that proxies
|
|
66
|
+
`websockets.Server` — `sockets`, `serve_forever`, `connections`, `is_serving`. If you know
|
|
67
|
+
`websockets`, you know this.
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
streamcast.Stream(name="", *, log=None, owns_log=False,
|
|
71
|
+
max_backlog=8192, max_replay=100_000)
|
|
72
|
+
streamcast.Stream.new(name="", *, root, schema, sort_by=None, config=None,
|
|
73
|
+
archive=None, s3=None, replay_archive=False,
|
|
74
|
+
max_backlog=8192, max_replay=100_000) # None = no bound
|
|
75
|
+
await stream.send(row) -> int | None # durable, then fan out
|
|
76
|
+
await stream.send_many(rows) -> list # ONE fsync for the group
|
|
77
|
+
stream.end_offset · stream.subscribers · stream.durable · stream.schema
|
|
78
|
+
|
|
79
|
+
streamcast.serve(streams, host, port, *, maintain=True, replicate=True, ...) -> Server
|
|
80
|
+
streamcast.connect(uri, *, offset=<unset>, cursor=None, cursor_uri=None,
|
|
81
|
+
catch_up=False, ...) -> Subscription
|
|
82
|
+
streamcast.to_arrow · streamcast.from_arrow · streamcast.Cursor · streamcast.EARLIEST
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Three deliberate exceptions:
|
|
86
|
+
|
|
87
|
+
- **Iterating yields `(offset, msg)`**, not `message`. The offset is what makes a reconnect
|
|
88
|
+
a resume rather than a restart, and a subscriber that has to ask for it separately will
|
|
89
|
+
forget to.
|
|
90
|
+
- **A subscription is read-only.** It has no `send`, rather than a `send` that raises.
|
|
91
|
+
Publishing is `Stream.send`, in the server's own process.
|
|
92
|
+
- **`compression` defaults to `None`**, where `websockets` defaults to `"deflate"`.
|
|
93
|
+
Not a LAN-versus-WAN judgement: permessage-deflate is **per connection** while the
|
|
94
|
+
encode is shared. `send` encodes a frame once and hands the same bytes to every
|
|
95
|
+
subscriber; deflate then compresses those identical bytes once per subscriber.
|
|
96
|
+
*Measured* on a six-column trade row — encode 0.564 µs once, deflate 3.454 µs each,
|
|
97
|
+
so CPU per message is 4 µs at one subscriber and 691 µs at 200. At 50 subscribers and
|
|
98
|
+
30,000 msg/s that is 1.5M compressions/s against roughly 290k a core can do, and the
|
|
99
|
+
symptom is subscribers hitting `max_backlog` and being dropped.
|
|
100
|
+
|
|
101
|
+
It compresses well when you want it — **5.8× smaller**, 112 bytes to 19, or 26.9 down
|
|
102
|
+
to 4.6 Mbit/s per subscriber at 30,000 msg/s. Pass `compression="deflate"` when
|
|
103
|
+
bandwidth costs more than CPU, which is a WAN with few subscribers. There is no middle
|
|
104
|
+
setting: without context takeover the same frames compress 1.1×, so "compress once and
|
|
105
|
+
share" is not available.
|
|
106
|
+
|
|
107
|
+
Routing is by `Stream.name`: `trades` is served at `/trades`, an unnamed stream at `/`.
|
|
108
|
+
`serve([trades, quotes])` serves both on one port.
|
|
109
|
+
|
|
110
|
+
Full reference in [`docs/API.md`](docs/API.md).
|
|
111
|
+
|
|
112
|
+
## The wire
|
|
113
|
+
|
|
114
|
+
Every frame is JSON text: a greeting, then an `[offset, msg]` pair per message.
|
|
115
|
+
|
|
116
|
+
```
|
|
117
|
+
{"streamcast":1,"stream":"trades","end_offset":1861,"replay":[1200,1861],"durable":true}
|
|
118
|
+
[1861,{"event_ts":1790038800123456,"price":85565.0,"amount":0.015,"side":0}]
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
The offset is positional, so `const [offset, msg] = JSON.parse(frame)` is a client in
|
|
122
|
+
another language and `wscat ws://localhost:8765/trades?offset=0` is a working subscriber
|
|
123
|
+
with none at all. Key order comes from the log's schema, so a replayed message is
|
|
124
|
+
byte-identical to the live one it repeats.
|
|
125
|
+
|
|
126
|
+
Encoding is [msgspec](https://github.com/jcrist/msgspec): 0.285 µs for a six-column row
|
|
127
|
+
against 5.815 µs for stdlib `json`.
|
|
128
|
+
|
|
129
|
+
`offset` is `null` on a stream with no log — nothing assigned one, and a per-process
|
|
130
|
+
counter would look like a resume cursor until the server restarted.
|
|
131
|
+
|
|
132
|
+
## Server
|
|
133
|
+
|
|
134
|
+
The schema is yours, declared in JSON Schema. `streamcast` is the only import a durable
|
|
135
|
+
stream needs.
|
|
136
|
+
|
|
137
|
+
```python
|
|
138
|
+
import asyncio, json, streamcast, websockets
|
|
139
|
+
|
|
140
|
+
SCHEMA = {
|
|
141
|
+
"type": "object",
|
|
142
|
+
"properties": {
|
|
143
|
+
"event_ts": {"type": "integer"},
|
|
144
|
+
"price": {"type": "number"},
|
|
145
|
+
"amount": {"type": "number"},
|
|
146
|
+
"side": {"type": "integer", "format": "int32"},
|
|
147
|
+
},
|
|
148
|
+
"required": ["event_ts", "price", "amount", "side"],
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async def main():
|
|
152
|
+
# Creates the log at data/trades, or opens it if it is already there.
|
|
153
|
+
stream = streamcast.Stream.new("trades", root="data", schema=SCHEMA,
|
|
154
|
+
sort_by=("event_ts",))
|
|
155
|
+
|
|
156
|
+
# Fan-out, sealing, compaction and WAL shipping: one call.
|
|
157
|
+
async with streamcast.serve(stream, "localhost", 8765):
|
|
158
|
+
async with websockets.connect("wss://ws.bitstamp.net") as feed:
|
|
159
|
+
await feed.send(SUBSCRIBE)
|
|
160
|
+
async for message in feed:
|
|
161
|
+
trade = json.loads(message)["data"]
|
|
162
|
+
await stream.send({ # a row, durable, then fanned out
|
|
163
|
+
"event_ts": int(trade["microtimestamp"]),
|
|
164
|
+
"price": float(trade["price"]),
|
|
165
|
+
"amount": float(trade["amount"]),
|
|
166
|
+
"side": int(trade["type"]),
|
|
167
|
+
})
|
|
168
|
+
|
|
169
|
+
asyncio.run(main())
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
`serve` starts everything the stream needs: a maintainer subprocess per stream with a log,
|
|
173
|
+
and litestream if the log has `wal_replication` on. Both are opt-out (`maintain=False`,
|
|
174
|
+
`replicate=False`). Without a maintainer nothing ever seals — litelink is explicit that
|
|
175
|
+
*"a maintainer is not optional"*.
|
|
176
|
+
|
|
177
|
+
`Stream.new` creates or opens the log; `Stream(log=handle)` takes one you opened yourself
|
|
178
|
+
and does no I/O. `streamcast.to_arrow(SCHEMA)` is the `pa.schema` if you want it.
|
|
179
|
+
|
|
180
|
+
What it captures is a table, queryable without streamcast:
|
|
181
|
+
|
|
182
|
+
```python
|
|
183
|
+
log.sql("SELECT count(*), max(price), sum(amount) FROM log").read_all()
|
|
184
|
+
log.scan(columns=["litelink_offset", "price"], where="side = 1") # prunes on statistics
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
### Surviving a feed that changes
|
|
188
|
+
|
|
189
|
+
`send` validates the row against the schema, so a feed that changes shape breaks capture —
|
|
190
|
+
a missing field, an unexpected type or a new key all raise, and that message is lost:
|
|
191
|
+
|
|
192
|
+
```
|
|
193
|
+
ValueError: row leaves non-nullable columns NULL: ['price']
|
|
194
|
+
ValueError: row names columns this log does not have: ['surprise']
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
If keeping every message matters more than strictness, declare the columns nullable, add
|
|
198
|
+
one for the raw message, and parse best-effort:
|
|
199
|
+
|
|
200
|
+
```python
|
|
201
|
+
SCHEMA = {
|
|
202
|
+
"type": "object",
|
|
203
|
+
"properties": {
|
|
204
|
+
"event_ts": {"type": ["integer", "null"]},
|
|
205
|
+
"price": {"type": ["number", "null"]},
|
|
206
|
+
"raw": {"type": ["string", "null"]},
|
|
207
|
+
},
|
|
208
|
+
"required": ["event_ts", "price", "raw"],
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
def number(value): # whatever the feed sent, or nothing
|
|
212
|
+
try:
|
|
213
|
+
return float(value)
|
|
214
|
+
except (TypeError, ValueError):
|
|
215
|
+
return None
|
|
216
|
+
|
|
217
|
+
def row(message: str) -> dict:
|
|
218
|
+
"""Best effort: take what parses, keep the whole message either way."""
|
|
219
|
+
try:
|
|
220
|
+
data = json.loads(message)["data"]
|
|
221
|
+
except (ValueError, KeyError, TypeError):
|
|
222
|
+
data = {}
|
|
223
|
+
|
|
224
|
+
return {
|
|
225
|
+
"event_ts": number(data.get("microtimestamp")),
|
|
226
|
+
"price": number(data.get("price")),
|
|
227
|
+
"raw": message,
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
await stream.send(row(message))
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
The row and its source land in **one append**, so a message is never captured without the
|
|
234
|
+
bytes it came from, and whatever the parse missed can be backfilled from the log later.
|
|
235
|
+
Run against a feed that drops a field, sends a non-trade event, and then sends invalid
|
|
236
|
+
JSON, all four rows are captured with the typed columns null and `raw` intact.
|
|
237
|
+
|
|
238
|
+
`required` still names every column, because in JSON Schema `required` is about the key
|
|
239
|
+
being present and `["number", "null"]` is what makes the value nullable — see
|
|
240
|
+
[`docs/API.md`](docs/API.md). Every column is nullable here precisely because best-effort
|
|
241
|
+
extraction means any of them can be missing.
|
|
242
|
+
|
|
243
|
+
Two costs, both real. A raw string column roughly doubles the log and compresses worse than
|
|
244
|
+
typed columns, which is [`SPEC.md`](docs/SPEC.md) §5's argument running the other way — this
|
|
245
|
+
is a deliberate trade, not a default. And subscribers receive the column too, since the wire
|
|
246
|
+
carries every declared column.
|
|
247
|
+
|
|
248
|
+
streamcast does not do the extraction for you. Feeds nest their payloads differently — the
|
|
249
|
+
example above reaches through `["data"]` — so a general extractor needs per-field paths, at
|
|
250
|
+
which point it is a feed-handler layer rather than a flag. It belongs in your feed handler,
|
|
251
|
+
where it already knows the feed.
|
|
252
|
+
|
|
253
|
+
### Serving the whole history
|
|
254
|
+
|
|
255
|
+
`replay_archive=True` with `max_replay=None` makes the server a complete gateway to the
|
|
256
|
+
log: no subscribe is refused for reaching too far back, and the server reads the archive on
|
|
257
|
+
the subscriber's behalf.
|
|
258
|
+
|
|
259
|
+
```python
|
|
260
|
+
stream = streamcast.Stream.new("trades", root="data", schema=SCHEMA,
|
|
261
|
+
archive="s3://bucket/prefix",
|
|
262
|
+
replay_archive=True, max_replay=None)
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
Every frame is still JSON over a plain WebSocket, so **a client in any language replays the
|
|
266
|
+
entire stream from offset 1** — no litelink, no Iceberg reader, no object-storage
|
|
267
|
+
credentials, nothing from this repo. `catch_up` exists because the default is the opposite;
|
|
268
|
+
this is the setting that makes it unnecessary.
|
|
269
|
+
|
|
270
|
+
It is not the default because of `max_backlog`. A replay is served before the live queue,
|
|
271
|
+
which fills behind it, so a subscriber reading ten million rows out of S3 accumulates live
|
|
272
|
+
messages for as long as that takes and is dropped the moment it catches up if it passed the
|
|
273
|
+
backlog on the way. Size the two together, or run it on a stream quiet enough that the
|
|
274
|
+
arithmetic does not bite. Each replay also holds a worker from the `to_thread` pool
|
|
275
|
+
(`min(32, cpu + 4)`) for its whole scan.
|
|
276
|
+
|
|
277
|
+
### Backpressure
|
|
278
|
+
|
|
279
|
+
`Stream.send` never awaits a consumer: it encodes the frame once and does one non-blocking
|
|
280
|
+
queue insert per subscriber. A consumer that stops reading fills its own queue, hits
|
|
281
|
+
`max_backlog`, and is **dropped**:
|
|
282
|
+
|
|
283
|
+
```
|
|
284
|
+
streamcast.TooSlow: the server dropped this subscriber for falling more than
|
|
285
|
+
8192 messages behind; resume at offset 20481
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
Dropping rather than buffering bounds the server's memory. Dropping rather than evicting
|
|
289
|
+
the oldest keeps what the subscriber received a contiguous prefix, so on a durable stream
|
|
290
|
+
the drop costs a reconnect and nothing else.
|
|
291
|
+
|
|
292
|
+
## Client
|
|
293
|
+
|
|
294
|
+
```python
|
|
295
|
+
async with streamcast.connect("ws://localhost:8765/trades") as stream:
|
|
296
|
+
async for offset, msg in stream:
|
|
297
|
+
print(offset, msg["price"], msg["amount"])
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
`msg` is exactly the row that was published — no offset key, nothing injected — so it can
|
|
301
|
+
be logged, forwarded, or appended to another stream whole. The parse happens once, at the
|
|
302
|
+
publisher.
|
|
303
|
+
|
|
304
|
+
### Resuming
|
|
305
|
+
|
|
306
|
+
The server records its frontier when a subscriber attaches, replays `[requested, frontier)`
|
|
307
|
+
from the log, then switches it to the live queue. Everything below the frontier is already
|
|
308
|
+
durable; everything above is already in the subscriber's queue. The two partition the
|
|
309
|
+
stream exactly — no gap, no duplicate.
|
|
310
|
+
|
|
311
|
+
```python
|
|
312
|
+
async with streamcast.connect(uri, cursor=".trades.offset") as stream:
|
|
313
|
+
async for offset, msg in stream:
|
|
314
|
+
handle(msg)
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
| keyword | what it does |
|
|
318
|
+
|---|---|
|
|
319
|
+
| `offset=N` | resume from `N` inclusive; `streamcast.EARLIEST` for everything the log holds |
|
|
320
|
+
| `cursor=path` | keep the resume point on disk — loaded at connect, saved as the loop runs |
|
|
321
|
+
| `cursor_uri=s3://…` | ship that cursor to object storage, so another box can resume |
|
|
322
|
+
| `catch_up=True` | read the gap from the archive when the server will not replay that far |
|
|
323
|
+
|
|
324
|
+
The cursor advances when you ask for the *next* message, and is not saved if the block
|
|
325
|
+
exits with an exception — so a crash re-delivers rather than skips. `sub.commit()` forces
|
|
326
|
+
it for a consumer that batches.
|
|
327
|
+
|
|
328
|
+
`catch_up` reads the archive with **nothing connected**, then opens the socket where the
|
|
329
|
+
archive ended, looping if the server moved on. Holding a socket through a long catch-up
|
|
330
|
+
would get the subscriber dropped for falling behind.
|
|
331
|
+
|
|
332
|
+
An offset the server cannot serve is refused, never silently rounded:
|
|
333
|
+
|
|
334
|
+
```
|
|
335
|
+
NotReplayable: offset 100 is below 5000, the earliest offset this stream's log
|
|
336
|
+
still serves. Reconnect with catch_up=True to read the rows between from the
|
|
337
|
+
archive if it still holds them — it will say so if it does not — or with
|
|
338
|
+
offset=streamcast.EARLIEST to take what is left and accept the gap.
|
|
339
|
+
```
|
|
340
|
+
|
|
341
|
+
Five `why` values — `not_durable`, `empty`, `ahead`, `too_old`, `evicted` — because the
|
|
342
|
+
caller's next move differs for each.
|
|
343
|
+
|
|
344
|
+
## Chaining
|
|
345
|
+
|
|
346
|
+
Each stage is a server, so a pipeline is servers end to end and every hop is independently
|
|
347
|
+
resumable:
|
|
348
|
+
|
|
349
|
+
```
|
|
350
|
+
market feed ─► streamcast ─► live runner ─► streamcast ─► dashboard
|
|
351
|
+
│ │
|
|
352
|
+
litelink litelink
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
Offsets are per server and are not translated between hops.
|
|
356
|
+
|
|
357
|
+
## What it is not
|
|
358
|
+
|
|
359
|
+
- **Not a message broker.** No fan-in: nothing publishes into a stream over the wire. No
|
|
360
|
+
topics beyond a name, no consumer groups, no acknowledgements. A subscriber needing
|
|
361
|
+
at-least-once with acks wants a queue.
|
|
362
|
+
- **Not tuned for high fan-out across a WAN.** `compression` defaults off because deflate
|
|
363
|
+
costs CPU per subscriber while the encode is shared — see the API section for the
|
|
364
|
+
numbers. Turn it on for few subscribers over a WAN; it is the wrong trade at fan-out.
|
|
365
|
+
- **Not a query interface.** `catch_up` covers resuming from further back than
|
|
366
|
+
`max_replay`; querying history is litelink directly, or any Iceberg engine.
|
|
367
|
+
- **Not a place for frames that are not rows.** A typed log has nowhere to put a
|
|
368
|
+
subscription ack or a heartbeat; the feed handler drops them.
|
|
369
|
+
|
|
370
|
+
## Not implemented yet
|
|
371
|
+
|
|
372
|
+
**Remote publishers.** `Stream.send` runs in the server's process; a client cannot publish
|
|
373
|
+
into a stream. **Registered intent** — one designated publisher and many read-only nodes —
|
|
374
|
+
is designed and unbuilt. **Arrow IPC as a negotiated wire format** would make a bulk
|
|
375
|
+
replay 492x cheaper to encode and 2.4x smaller, at the cost of the `wscat` affordance.
|
|
376
|
+
See [`docs/SPEC.md`](docs/SPEC.md) §9.
|
|
377
|
+
|
|
378
|
+
## Documentation
|
|
379
|
+
|
|
380
|
+
- [`docs/API.md`](docs/API.md) — every public call, on one page
|
|
381
|
+
- [`docs/SPEC.md`](docs/SPEC.md) — the design, the protocol, and the invariants
|
|
382
|
+
- [`examples/`](examples/) — a live public feed through a server, and a resuming consumer
|
|
383
|
+
- [`CONTRIBUTING.md`](CONTRIBUTING.md) — setup, the gates, and what a good PR looks like
|
|
384
|
+
|
|
385
|
+
## Development
|
|
386
|
+
|
|
387
|
+
```bash
|
|
388
|
+
just bootstrap # uv sync + git hooks
|
|
389
|
+
just check # lint + format-check + typecheck + tests
|
|
390
|
+
just --list # the rest
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
Most of the suite needs no network, container or credentials. The replication and
|
|
394
|
+
catch-up tiers do: `just rustfs` starts a local S3 endpoint and `just check-all` runs
|
|
395
|
+
every gate against it. Without one those tests skip, and a skip is not a pass.
|
|
396
|
+
|
|
397
|
+
## License
|
|
398
|
+
|
|
399
|
+
Apache License 2.0 — see [LICENSE](LICENSE) and [NOTICE](NOTICE).
|