altengine 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.
@@ -0,0 +1,33 @@
1
+ # build output
2
+ /cli/altengine
3
+ /cli/dist/
4
+ /bin/
5
+
6
+ # default local data directory (any depth — tests/harnesses may create their own)
7
+ .altengine/
8
+ .altenginedev/
9
+
10
+ # JS
11
+ node_modules/
12
+ /js/dist/
13
+ /js/test/.bin/
14
+
15
+ # go.work personal overrides
16
+ go.work.sum
17
+
18
+ # editor / OS
19
+ .DS_Store
20
+ *.swp
21
+
22
+ # Python
23
+ /python/.venv/
24
+ __pycache__/
25
+ *.egg-info/
26
+ /python/dist/
27
+ .pytest_cache/
28
+
29
+ # PHP
30
+ /php/vendor/
31
+ /php/composer.lock
32
+ .phpunit.cache/
33
+ .phpunit.result.cache
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 altlimit
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,183 @@
1
+ Metadata-Version: 2.5
2
+ Name: altengine
3
+ Version: 0.1.0
4
+ Summary: Official Python SDK for altengine - managed datastore, search, and realtime channels
5
+ Project-URL: Homepage, https://www.altengine.net
6
+ Project-URL: Repository, https://github.com/altlimit/altengine
7
+ Author: altlimit
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: altengine,datastore,pubsub,realtime,search
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Topic :: Database
16
+ Classifier: Topic :: Internet :: WWW/HTTP :: Indexing/Search
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.9
19
+ Requires-Dist: httpx>=0.25
20
+ Provides-Extra: ws
21
+ Requires-Dist: websockets>=12; extra == 'ws'
22
+ Description-Content-Type: text/markdown
23
+
24
+ # altengine Python SDK
25
+
26
+ Official Python SDK for [altengine](https://www.altengine.net) — managed
27
+ **datastore**, **search**, and realtime **channels** behind one API key.
28
+ Built on `httpx` (sync + async); the WebSocket subscriber uses `websockets`.
29
+
30
+ It covers those three services only. Auth, blob, containers and automation have clients in the
31
+ JS SDK; from Python, call their REST API with the same API key.
32
+
33
+ Install a registry release with `pip install altengine`. To install from source instead, run
34
+
35
+ ```bash
36
+ # HTTP clients
37
+ pip install "altengine @ git+https://github.com/altlimit/altengine#subdirectory=python"
38
+ # + the managed WebSocket subscriber
39
+ pip install "altengine[ws] @ git+https://github.com/altlimit/altengine#subdirectory=python"
40
+ ```
41
+
42
+ ## Setup
43
+
44
+ ```python
45
+ from altengine import AltEngine
46
+
47
+ ae = AltEngine(api_key="ae_...") # production: https://api.altengine.net
48
+ ```
49
+
50
+ Everything is overridable, nothing is required:
51
+
52
+ - `api_key` — falls back to the `ALTENGINE_API_KEY` env var
53
+ - `dev=True` — target the [local emulator](https://github.com/altlimit/altengine)
54
+ at `http://127.0.0.1:9191` (`altengine dev`)
55
+ - `base_url` — explicit origin; also settable via the `ALTENGINE_URL` env var
56
+ (resolution: `base_url` → `dev` → `ALTENGINE_URL` → production)
57
+
58
+ There is an async twin with the same surface:
59
+
60
+ ```python
61
+ from altengine import AsyncAltEngine
62
+
63
+ async with AsyncAltEngine(api_key="ae_...") as ae:
64
+ doc = await ae.datastore("myapp").get("todos", "t1")
65
+ ```
66
+
67
+ Requests and responses are **wire-verbatim dicts** — what the REST API
68
+ documents is exactly what you pass and get back. Retryable failures (429 with
69
+ `Retry-After`, 502/503/504, network errors) are retried up to 3 times with
70
+ jittered backoff — except transactions, publishes and datastore puts with server-generated keys, which are never
71
+ auto-retried. Errors raise `AltEngineError` with `code`, `status`, `details`,
72
+ and `retry_after`.
73
+
74
+ ## Datastore
75
+
76
+ ```python
77
+ db = ae.datastore("myapp", namespace="prod")
78
+
79
+ keys = db.put("todos", [{"data": {"title": "ship SDK", "done": False}}])
80
+ doc = db.get("todos", keys[0]) # None when missing
81
+ docs = db.get("todos", keys) # list in → list out, None for missing
82
+ db.delete("todos", keys) # missing keys are no-ops
83
+
84
+ # Queries (query_all pages cursors for you)
85
+ page = db.query(
86
+ "todos",
87
+ where=[{"field": "done", "op": "=", "value": False}],
88
+ order=[{"field": "priority", "dir": "desc"}],
89
+ limit=100,
90
+ )
91
+ for doc in db.query_all("todos", where=[{"field": "owner", "op": "=", "value": "ana"}]):
92
+ ...
93
+
94
+ # Aggregates
95
+ res = db.aggregate(
96
+ "todos",
97
+ group=["owner"],
98
+ metrics=[{"fn": "count", "as": "n"}, {"fn": "sum", "field": "priority", "as": "total"}],
99
+ )
100
+
101
+ # Transactions (atomic within a namespace; a failed check raises a 409)
102
+ db.transaction([
103
+ {"op": "check", "collection": "users", "key": "u1", "exists": True},
104
+ {"op": "mutate", "collection": "counters", "key": "todos", "increment": {"total": 1}, "upsert": True},
105
+ ])
106
+
107
+ # Indexes
108
+ db.create_index("todos", ["owner", "created:desc"])
109
+ ```
110
+
111
+ ## Search
112
+
113
+ ```python
114
+ from altengine import f, facet
115
+
116
+ idx = ae.search("myapp").index("products")
117
+
118
+ idx.put([{
119
+ "id": "p1",
120
+ "fields": [
121
+ f.text("title", "Blue Suede Shoes"),
122
+ f.atom("sku", "BS-001"),
123
+ f.number("price", 59),
124
+ f.date("added", datetime.now(timezone.utc)),
125
+ f.geo("store", 37.77, -122.41),
126
+ ],
127
+ "facets": [facet.atom("category", "shoes"), facet.number("price", 59)],
128
+ }])
129
+
130
+ doc = idx.get("p1") # None when missing
131
+ docs = idx.get(["p1", "nope"]) # list in → list out, None for missing
132
+
133
+ res = idx.search(
134
+ "shoes price<100",
135
+ facets=["category"],
136
+ snippet={"fields": ["title"]},
137
+ sort=[{"expr": "price"}],
138
+ limit=20,
139
+ )
140
+
141
+ for hit in idx.search_all("shoes"): # cursor-paged
142
+ ...
143
+ ```
144
+
145
+ ## Channels
146
+
147
+ Server side — mint subscriber tokens, publish, read presence:
148
+
149
+ ```python
150
+ ch = ae.channel("myapp")
151
+ tok = ch.create_token(channels=["room:1"], ttl_seconds=3600, presence_id="u42")
152
+ delivered = ch.publish("room:1", {"hello": "world"})
153
+ roster = ch.presence("room:1")
154
+ ```
155
+
156
+ Managed WebSocket subscriber (asyncio; auto-reconnect, resubscribe, keepalive):
157
+
158
+ ```python
159
+ from altengine import ChannelSocket
160
+
161
+ sock = ChannelSocket(get_token=lambda: ch.create_token(channels=["room:2"]))
162
+ await sock.connect()
163
+ async for msg in sock.messages():
164
+ print(msg["channel"], msg["data"])
165
+ ```
166
+
167
+ ## Local development
168
+
169
+ Run the [altengine emulator](https://github.com/altlimit/altengine) and
170
+ construct the client with `dev=True` (or set `ALTENGINE_URL`) — any non-empty
171
+ API key works:
172
+
173
+ ```bash
174
+ alt install altlimit/altengine && altengine dev
175
+ ```
176
+
177
+ The conformance suite runs against a spawned emulator:
178
+
179
+ ```bash
180
+ pip install -e ".[ws]" pytest && pytest
181
+ ```
182
+
183
+ Get an API key and instances for production at [www.altengine.net](https://www.altengine.net).
@@ -0,0 +1,160 @@
1
+ # altengine Python SDK
2
+
3
+ Official Python SDK for [altengine](https://www.altengine.net) — managed
4
+ **datastore**, **search**, and realtime **channels** behind one API key.
5
+ Built on `httpx` (sync + async); the WebSocket subscriber uses `websockets`.
6
+
7
+ It covers those three services only. Auth, blob, containers and automation have clients in the
8
+ JS SDK; from Python, call their REST API with the same API key.
9
+
10
+ Install a registry release with `pip install altengine`. To install from source instead, run
11
+
12
+ ```bash
13
+ # HTTP clients
14
+ pip install "altengine @ git+https://github.com/altlimit/altengine#subdirectory=python"
15
+ # + the managed WebSocket subscriber
16
+ pip install "altengine[ws] @ git+https://github.com/altlimit/altengine#subdirectory=python"
17
+ ```
18
+
19
+ ## Setup
20
+
21
+ ```python
22
+ from altengine import AltEngine
23
+
24
+ ae = AltEngine(api_key="ae_...") # production: https://api.altengine.net
25
+ ```
26
+
27
+ Everything is overridable, nothing is required:
28
+
29
+ - `api_key` — falls back to the `ALTENGINE_API_KEY` env var
30
+ - `dev=True` — target the [local emulator](https://github.com/altlimit/altengine)
31
+ at `http://127.0.0.1:9191` (`altengine dev`)
32
+ - `base_url` — explicit origin; also settable via the `ALTENGINE_URL` env var
33
+ (resolution: `base_url` → `dev` → `ALTENGINE_URL` → production)
34
+
35
+ There is an async twin with the same surface:
36
+
37
+ ```python
38
+ from altengine import AsyncAltEngine
39
+
40
+ async with AsyncAltEngine(api_key="ae_...") as ae:
41
+ doc = await ae.datastore("myapp").get("todos", "t1")
42
+ ```
43
+
44
+ Requests and responses are **wire-verbatim dicts** — what the REST API
45
+ documents is exactly what you pass and get back. Retryable failures (429 with
46
+ `Retry-After`, 502/503/504, network errors) are retried up to 3 times with
47
+ jittered backoff — except transactions, publishes and datastore puts with server-generated keys, which are never
48
+ auto-retried. Errors raise `AltEngineError` with `code`, `status`, `details`,
49
+ and `retry_after`.
50
+
51
+ ## Datastore
52
+
53
+ ```python
54
+ db = ae.datastore("myapp", namespace="prod")
55
+
56
+ keys = db.put("todos", [{"data": {"title": "ship SDK", "done": False}}])
57
+ doc = db.get("todos", keys[0]) # None when missing
58
+ docs = db.get("todos", keys) # list in → list out, None for missing
59
+ db.delete("todos", keys) # missing keys are no-ops
60
+
61
+ # Queries (query_all pages cursors for you)
62
+ page = db.query(
63
+ "todos",
64
+ where=[{"field": "done", "op": "=", "value": False}],
65
+ order=[{"field": "priority", "dir": "desc"}],
66
+ limit=100,
67
+ )
68
+ for doc in db.query_all("todos", where=[{"field": "owner", "op": "=", "value": "ana"}]):
69
+ ...
70
+
71
+ # Aggregates
72
+ res = db.aggregate(
73
+ "todos",
74
+ group=["owner"],
75
+ metrics=[{"fn": "count", "as": "n"}, {"fn": "sum", "field": "priority", "as": "total"}],
76
+ )
77
+
78
+ # Transactions (atomic within a namespace; a failed check raises a 409)
79
+ db.transaction([
80
+ {"op": "check", "collection": "users", "key": "u1", "exists": True},
81
+ {"op": "mutate", "collection": "counters", "key": "todos", "increment": {"total": 1}, "upsert": True},
82
+ ])
83
+
84
+ # Indexes
85
+ db.create_index("todos", ["owner", "created:desc"])
86
+ ```
87
+
88
+ ## Search
89
+
90
+ ```python
91
+ from altengine import f, facet
92
+
93
+ idx = ae.search("myapp").index("products")
94
+
95
+ idx.put([{
96
+ "id": "p1",
97
+ "fields": [
98
+ f.text("title", "Blue Suede Shoes"),
99
+ f.atom("sku", "BS-001"),
100
+ f.number("price", 59),
101
+ f.date("added", datetime.now(timezone.utc)),
102
+ f.geo("store", 37.77, -122.41),
103
+ ],
104
+ "facets": [facet.atom("category", "shoes"), facet.number("price", 59)],
105
+ }])
106
+
107
+ doc = idx.get("p1") # None when missing
108
+ docs = idx.get(["p1", "nope"]) # list in → list out, None for missing
109
+
110
+ res = idx.search(
111
+ "shoes price<100",
112
+ facets=["category"],
113
+ snippet={"fields": ["title"]},
114
+ sort=[{"expr": "price"}],
115
+ limit=20,
116
+ )
117
+
118
+ for hit in idx.search_all("shoes"): # cursor-paged
119
+ ...
120
+ ```
121
+
122
+ ## Channels
123
+
124
+ Server side — mint subscriber tokens, publish, read presence:
125
+
126
+ ```python
127
+ ch = ae.channel("myapp")
128
+ tok = ch.create_token(channels=["room:1"], ttl_seconds=3600, presence_id="u42")
129
+ delivered = ch.publish("room:1", {"hello": "world"})
130
+ roster = ch.presence("room:1")
131
+ ```
132
+
133
+ Managed WebSocket subscriber (asyncio; auto-reconnect, resubscribe, keepalive):
134
+
135
+ ```python
136
+ from altengine import ChannelSocket
137
+
138
+ sock = ChannelSocket(get_token=lambda: ch.create_token(channels=["room:2"]))
139
+ await sock.connect()
140
+ async for msg in sock.messages():
141
+ print(msg["channel"], msg["data"])
142
+ ```
143
+
144
+ ## Local development
145
+
146
+ Run the [altengine emulator](https://github.com/altlimit/altengine) and
147
+ construct the client with `dev=True` (or set `ALTENGINE_URL`) — any non-empty
148
+ API key works:
149
+
150
+ ```bash
151
+ alt install altlimit/altengine && altengine dev
152
+ ```
153
+
154
+ The conformance suite runs against a spawned emulator:
155
+
156
+ ```bash
157
+ pip install -e ".[ws]" pytest && pytest
158
+ ```
159
+
160
+ Get an API key and instances for production at [www.altengine.net](https://www.altengine.net).
@@ -0,0 +1,36 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "altengine"
7
+ version = "0.1.0"
8
+ description = "Official Python SDK for altengine - managed datastore, search, and realtime channels"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.9"
12
+ authors = [{ name = "altlimit" }]
13
+ keywords = ["altengine", "search", "datastore", "pubsub", "realtime"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3 :: Only",
19
+ "Topic :: Database",
20
+ "Topic :: Internet :: WWW/HTTP :: Indexing/Search",
21
+ "Typing :: Typed",
22
+ ]
23
+ dependencies = ["httpx>=0.25"]
24
+
25
+ [project.optional-dependencies]
26
+ ws = ["websockets>=12"]
27
+
28
+ [project.urls]
29
+ Homepage = "https://www.altengine.net"
30
+ Repository = "https://github.com/altlimit/altengine"
31
+
32
+ [tool.hatch.build.targets.wheel]
33
+ packages = ["src/altengine"]
34
+
35
+ [tool.pytest.ini_options]
36
+ testpaths = ["tests"]
@@ -0,0 +1,140 @@
1
+ """altengine — official Python SDK for https://www.altengine.net
2
+ (managed datastore, search, and realtime channels behind one API key).
3
+
4
+ from altengine import AltEngine, f, facet
5
+
6
+ ae = AltEngine(api_key="ae_...") # production api.altengine.net
7
+ # ae = AltEngine(dev=True, api_key="dev") # local `altengine dev`
8
+
9
+ db = ae.datastore("myapp")
10
+ keys = db.put("todos", [{"data": {"title": "ship SDK"}}])
11
+
12
+ idx = ae.search("myapp").index("products")
13
+ idx.put([{"fields": [f.text("title", "Blue Shoes"), f.number("price", 59)]}])
14
+
15
+ ch = ae.channel("myapp")
16
+ tok = ch.create_token(channels=["room:1"])
17
+
18
+ Async twin: ``AsyncAltEngine`` (same surface, awaitable). The managed
19
+ WebSocket subscriber is ``ChannelSocket`` (``pip install altengine[ws]``).
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from typing import Optional
25
+
26
+ import httpx
27
+
28
+ from ._http import DEFAULT_BASE_URL, DEV_BASE_URL, AsyncHttp, Http
29
+ from .channel import AsyncChannelClient, ChannelClient
30
+ from .datastore import AsyncDatastoreClient, DatastoreClient
31
+ from .errors import AltEngineError, AltEngineNetworkError
32
+ from .fields import f, facet
33
+ from .search import AsyncSearchClient, AsyncSearchIndex, SearchClient, SearchIndex
34
+ from .socket import ChannelSocket, ChannelSocketError
35
+
36
+ __version__ = "0.1.0"
37
+
38
+ __all__ = [
39
+ "AltEngine",
40
+ "AsyncAltEngine",
41
+ "AltEngineError",
42
+ "AltEngineNetworkError",
43
+ "ChannelSocket",
44
+ "ChannelSocketError",
45
+ "DatastoreClient",
46
+ "AsyncDatastoreClient",
47
+ "SearchClient",
48
+ "SearchIndex",
49
+ "AsyncSearchClient",
50
+ "AsyncSearchIndex",
51
+ "ChannelClient",
52
+ "AsyncChannelClient",
53
+ "DEFAULT_BASE_URL",
54
+ "DEV_BASE_URL",
55
+ "f",
56
+ "facet",
57
+ ]
58
+
59
+
60
+ class AltEngine:
61
+ """Synchronous entry point.
62
+
63
+ - ``api_key`` — falls back to the ``ALTENGINE_API_KEY`` env var
64
+ - ``dev=True`` — target the local emulator (``altengine dev``)
65
+ - ``base_url`` — explicit origin; also settable via ``ALTENGINE_URL``
66
+ (resolution: ``base_url`` → ``dev`` → ``ALTENGINE_URL`` → production)
67
+
68
+ Retryable failures (429 with Retry-After, 502/503/504, network) are
69
+ retried up to 3 times with jittered backoff — except transactions and
70
+ publishes, which are never auto-retried.
71
+ """
72
+
73
+ def __init__(
74
+ self,
75
+ api_key: Optional[str] = None,
76
+ base_url: Optional[str] = None,
77
+ dev: bool = False,
78
+ timeout: float = 30.0,
79
+ max_attempts: int = 3,
80
+ client: Optional[httpx.Client] = None,
81
+ ) -> None:
82
+ self._http = Http(
83
+ api_key=api_key, base_url=base_url, dev=dev, timeout=timeout, max_attempts=max_attempts, client=client
84
+ )
85
+
86
+ def datastore(self, instance: str, namespace: str = "") -> DatastoreClient:
87
+ """Client for a datastore instance (namespace-bound; default ``""``)."""
88
+ return DatastoreClient(self._http, instance, namespace)
89
+
90
+ def search(self, instance: str, namespace: str = "") -> SearchClient:
91
+ """Client for a search instance (namespace-bound; default ``""``)."""
92
+ return SearchClient(self._http, instance, namespace)
93
+
94
+ def channel(self, instance: str) -> ChannelClient:
95
+ """Server-side client for a channel instance (tokens, publish, presence)."""
96
+ return ChannelClient(self._http, instance)
97
+
98
+ def close(self) -> None:
99
+ self._http.close()
100
+
101
+ def __enter__(self) -> "AltEngine":
102
+ return self
103
+
104
+ def __exit__(self, *exc: object) -> None:
105
+ self.close()
106
+
107
+
108
+ class AsyncAltEngine:
109
+ """Asynchronous entry point — same surface as :class:`AltEngine`, awaitable."""
110
+
111
+ def __init__(
112
+ self,
113
+ api_key: Optional[str] = None,
114
+ base_url: Optional[str] = None,
115
+ dev: bool = False,
116
+ timeout: float = 30.0,
117
+ max_attempts: int = 3,
118
+ client: Optional[httpx.AsyncClient] = None,
119
+ ) -> None:
120
+ self._http = AsyncHttp(
121
+ api_key=api_key, base_url=base_url, dev=dev, timeout=timeout, max_attempts=max_attempts, client=client
122
+ )
123
+
124
+ def datastore(self, instance: str, namespace: str = "") -> AsyncDatastoreClient:
125
+ return AsyncDatastoreClient(self._http, instance, namespace)
126
+
127
+ def search(self, instance: str, namespace: str = "") -> AsyncSearchClient:
128
+ return AsyncSearchClient(self._http, instance, namespace)
129
+
130
+ def channel(self, instance: str) -> AsyncChannelClient:
131
+ return AsyncChannelClient(self._http, instance)
132
+
133
+ async def close(self) -> None:
134
+ await self._http.close()
135
+
136
+ async def __aenter__(self) -> "AsyncAltEngine":
137
+ return self
138
+
139
+ async def __aexit__(self, *exc: object) -> None:
140
+ await self.close()