lyhnidos 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.
- lyhnidos-0.2.0/PKG-INFO +134 -0
- lyhnidos-0.2.0/README.md +105 -0
- lyhnidos-0.2.0/lyhnidos/__init__.py +27 -0
- lyhnidos-0.2.0/lyhnidos/apps.py +321 -0
- lyhnidos-0.2.0/lyhnidos/connector.py +233 -0
- lyhnidos-0.2.0/lyhnidos.egg-info/PKG-INFO +134 -0
- lyhnidos-0.2.0/lyhnidos.egg-info/SOURCES.txt +11 -0
- lyhnidos-0.2.0/lyhnidos.egg-info/dependency_links.txt +1 -0
- lyhnidos-0.2.0/lyhnidos.egg-info/requires.txt +15 -0
- lyhnidos-0.2.0/lyhnidos.egg-info/top_level.txt +1 -0
- lyhnidos-0.2.0/pyproject.toml +50 -0
- lyhnidos-0.2.0/setup.cfg +4 -0
- lyhnidos-0.2.0/tests/test_apps.py +366 -0
lyhnidos-0.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: lyhnidos
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Python client for Lyhnidos Geo: an admin SDK for the app platform, and (with the [data] extra) Apache Arrow, DuckDB and Ibis integration
|
|
5
|
+
Author: Lyhnidos Geo Authors
|
|
6
|
+
License-Expression: MIT OR Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://lyhnidos.dev
|
|
8
|
+
Project-URL: Documentation, https://lyhnidos.dev/studio
|
|
9
|
+
Keywords: gis,geospatial,ogc,arcgis,arrow,duckdb,lyhnidos
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: GIS
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
Requires-Dist: requests>=2.28.0
|
|
17
|
+
Provides-Extra: data
|
|
18
|
+
Requires-Dist: pyarrow>=14.0.0; extra == "data"
|
|
19
|
+
Requires-Dist: duckdb>=1.0.0; extra == "data"
|
|
20
|
+
Requires-Dist: ibis-framework>=9.0.0; extra == "data"
|
|
21
|
+
Provides-Extra: all
|
|
22
|
+
Requires-Dist: pyarrow>=14.0.0; extra == "all"
|
|
23
|
+
Requires-Dist: duckdb>=1.0.0; extra == "all"
|
|
24
|
+
Requires-Dist: ibis-framework>=9.0.0; extra == "all"
|
|
25
|
+
Requires-Dist: polars>=1.0.0; extra == "all"
|
|
26
|
+
Requires-Dist: pandas>=2.0.0; extra == "all"
|
|
27
|
+
Requires-Dist: geopandas>=1.0.0; extra == "all"
|
|
28
|
+
Requires-Dist: shapely>=2.0.0; extra == "all"
|
|
29
|
+
|
|
30
|
+
# lyhnidos
|
|
31
|
+
|
|
32
|
+
Python client for **Lyhnidos Geo** — a spatial database platform with OGC API
|
|
33
|
+
Features and ArcGIS FeatureServer interfaces, an app platform (end-user
|
|
34
|
+
sign-in and row rules), and Apache Arrow streaming.
|
|
35
|
+
|
|
36
|
+
## Installation
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install lyhnidos # admin SDK + HTTP client (needs only `requests`)
|
|
40
|
+
pip install "lyhnidos[data]" # + Apache Arrow streaming, DuckDB and Ibis
|
|
41
|
+
pip install "lyhnidos[all]" # + Polars, pandas, GeoPandas and Shapely
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Python 3.10 or newer. Features that need an extra say which one when it is
|
|
45
|
+
missing.
|
|
46
|
+
|
|
47
|
+
## Quickstart
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from lyhnidos import LyhnidosClient
|
|
51
|
+
|
|
52
|
+
client = LyhnidosClient(
|
|
53
|
+
"https://api.lyhnidos.dev",
|
|
54
|
+
database="my_database",
|
|
55
|
+
auth_token="lyhn_xxxxxxxxxxxx", # an API key from Studio
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
# SQL with the engine's spatial functions
|
|
59
|
+
rows = client.query(
|
|
60
|
+
"SELECT name FROM parcels "
|
|
61
|
+
"WHERE ST_DWithin4D(geom, ST_Point4D(144.983, -37.801, 0.0, 0.0), 500, 1e12) = 1"
|
|
62
|
+
)
|
|
63
|
+
print(rows["rows"])
|
|
64
|
+
|
|
65
|
+
# Import GeoJSON or CSV into a table
|
|
66
|
+
with open("parcels.geojson") as f:
|
|
67
|
+
client.import_data(format="geojson", data=f.read(), table_name="parcels")
|
|
68
|
+
|
|
69
|
+
# Requires the [data] extra: stream a table as Apache Arrow, or into DuckDB
|
|
70
|
+
arrow_table = client.fetch_arrow("parcels")
|
|
71
|
+
con = client.to_duckdb("parcels")
|
|
72
|
+
print(con.execute("SELECT count(*) FROM parcels").fetchall())
|
|
73
|
+
|
|
74
|
+
# Requires the [all] extra: DataFrames
|
|
75
|
+
df = client.to_polars("parcels")
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
`semantic_search(table, search_text, lat, lng, radius_meters=1000)` ranks
|
|
79
|
+
features near a point by text similarity, for tables that carry an embedding
|
|
80
|
+
column.
|
|
81
|
+
|
|
82
|
+
## App platform admin
|
|
83
|
+
|
|
84
|
+
`lyhnidos.AppsAdmin` administers a workspace's app platform: the app-user
|
|
85
|
+
pool, publishable keys, app users and their sessions, usage, and row rules.
|
|
86
|
+
It calls the engine's `/v1/tenants/{id}/...` admin routes with a
|
|
87
|
+
workspace-scoped admin key or a fleet key -- never an app's own end-user
|
|
88
|
+
surface (`/v1/apps/{workspace}/...`).
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
from lyhnidos import AppsAdmin, LyhnidosError
|
|
92
|
+
|
|
93
|
+
admin = AppsAdmin("https://api.lyhnidos.dev", api_key="lyhn_xxxxxxxxxxxx", workspace="acme")
|
|
94
|
+
|
|
95
|
+
# Mint a publishable key (shown once -- an app's own front end carries this).
|
|
96
|
+
key = admin.create_publishable_key("Marketing site")
|
|
97
|
+
print(key["key"], key["key_prefix"])
|
|
98
|
+
|
|
99
|
+
# Invite a user into the pool.
|
|
100
|
+
admin.invite_user("new-user@example.com", role="member")
|
|
101
|
+
|
|
102
|
+
# Let signed-in users read and insert only their own rows of `notes`.
|
|
103
|
+
admin.put_table_rules(
|
|
104
|
+
"acme_main",
|
|
105
|
+
"notes",
|
|
106
|
+
enabled=True,
|
|
107
|
+
rules=[
|
|
108
|
+
{"role": "*", "operation": "read", "preset": {"kind": "own_rows"}},
|
|
109
|
+
{"role": "*", "operation": "insert", "preset": {"kind": "own_rows"}},
|
|
110
|
+
],
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
try:
|
|
114
|
+
admin.get_user("does-not-exist")
|
|
115
|
+
except LyhnidosError as error:
|
|
116
|
+
print(error.status, error.code) # 404 not_found
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
`update_pool(**changes)` reads the pool, merges the given top-level fields
|
|
120
|
+
into it, and writes it back -- so changing `site_url` alone never drops
|
|
121
|
+
`allowed_origins` or the rest of the pool a plain `put_pool` would otherwise
|
|
122
|
+
need restated in full.
|
|
123
|
+
|
|
124
|
+
The write is conditional: `update_pool` sends the `revision` its read returned as
|
|
125
|
+
`If-Match`, so if another administrator (Studio, a second script) changed the pool
|
|
126
|
+
in between, the server answers `409 pool_changed` and `update_pool` raises
|
|
127
|
+
`LyhnidosError` rather than overwriting their change; read again and retry.
|
|
128
|
+
`put_pool(pool)` stays unconditional (last writer wins) unless you pass
|
|
129
|
+
`if_match=<revision from get_pool()>`. Against a server that does not report a
|
|
130
|
+
`revision` (older than 0.6.13) both are last-writer-wins.
|
|
131
|
+
|
|
132
|
+
## License
|
|
133
|
+
|
|
134
|
+
MIT OR Apache-2.0
|
lyhnidos-0.2.0/README.md
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
# lyhnidos
|
|
2
|
+
|
|
3
|
+
Python client for **Lyhnidos Geo** — a spatial database platform with OGC API
|
|
4
|
+
Features and ArcGIS FeatureServer interfaces, an app platform (end-user
|
|
5
|
+
sign-in and row rules), and Apache Arrow streaming.
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install lyhnidos # admin SDK + HTTP client (needs only `requests`)
|
|
11
|
+
pip install "lyhnidos[data]" # + Apache Arrow streaming, DuckDB and Ibis
|
|
12
|
+
pip install "lyhnidos[all]" # + Polars, pandas, GeoPandas and Shapely
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Python 3.10 or newer. Features that need an extra say which one when it is
|
|
16
|
+
missing.
|
|
17
|
+
|
|
18
|
+
## Quickstart
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
from lyhnidos import LyhnidosClient
|
|
22
|
+
|
|
23
|
+
client = LyhnidosClient(
|
|
24
|
+
"https://api.lyhnidos.dev",
|
|
25
|
+
database="my_database",
|
|
26
|
+
auth_token="lyhn_xxxxxxxxxxxx", # an API key from Studio
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
# SQL with the engine's spatial functions
|
|
30
|
+
rows = client.query(
|
|
31
|
+
"SELECT name FROM parcels "
|
|
32
|
+
"WHERE ST_DWithin4D(geom, ST_Point4D(144.983, -37.801, 0.0, 0.0), 500, 1e12) = 1"
|
|
33
|
+
)
|
|
34
|
+
print(rows["rows"])
|
|
35
|
+
|
|
36
|
+
# Import GeoJSON or CSV into a table
|
|
37
|
+
with open("parcels.geojson") as f:
|
|
38
|
+
client.import_data(format="geojson", data=f.read(), table_name="parcels")
|
|
39
|
+
|
|
40
|
+
# Requires the [data] extra: stream a table as Apache Arrow, or into DuckDB
|
|
41
|
+
arrow_table = client.fetch_arrow("parcels")
|
|
42
|
+
con = client.to_duckdb("parcels")
|
|
43
|
+
print(con.execute("SELECT count(*) FROM parcels").fetchall())
|
|
44
|
+
|
|
45
|
+
# Requires the [all] extra: DataFrames
|
|
46
|
+
df = client.to_polars("parcels")
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
`semantic_search(table, search_text, lat, lng, radius_meters=1000)` ranks
|
|
50
|
+
features near a point by text similarity, for tables that carry an embedding
|
|
51
|
+
column.
|
|
52
|
+
|
|
53
|
+
## App platform admin
|
|
54
|
+
|
|
55
|
+
`lyhnidos.AppsAdmin` administers a workspace's app platform: the app-user
|
|
56
|
+
pool, publishable keys, app users and their sessions, usage, and row rules.
|
|
57
|
+
It calls the engine's `/v1/tenants/{id}/...` admin routes with a
|
|
58
|
+
workspace-scoped admin key or a fleet key -- never an app's own end-user
|
|
59
|
+
surface (`/v1/apps/{workspace}/...`).
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
from lyhnidos import AppsAdmin, LyhnidosError
|
|
63
|
+
|
|
64
|
+
admin = AppsAdmin("https://api.lyhnidos.dev", api_key="lyhn_xxxxxxxxxxxx", workspace="acme")
|
|
65
|
+
|
|
66
|
+
# Mint a publishable key (shown once -- an app's own front end carries this).
|
|
67
|
+
key = admin.create_publishable_key("Marketing site")
|
|
68
|
+
print(key["key"], key["key_prefix"])
|
|
69
|
+
|
|
70
|
+
# Invite a user into the pool.
|
|
71
|
+
admin.invite_user("new-user@example.com", role="member")
|
|
72
|
+
|
|
73
|
+
# Let signed-in users read and insert only their own rows of `notes`.
|
|
74
|
+
admin.put_table_rules(
|
|
75
|
+
"acme_main",
|
|
76
|
+
"notes",
|
|
77
|
+
enabled=True,
|
|
78
|
+
rules=[
|
|
79
|
+
{"role": "*", "operation": "read", "preset": {"kind": "own_rows"}},
|
|
80
|
+
{"role": "*", "operation": "insert", "preset": {"kind": "own_rows"}},
|
|
81
|
+
],
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
try:
|
|
85
|
+
admin.get_user("does-not-exist")
|
|
86
|
+
except LyhnidosError as error:
|
|
87
|
+
print(error.status, error.code) # 404 not_found
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
`update_pool(**changes)` reads the pool, merges the given top-level fields
|
|
91
|
+
into it, and writes it back -- so changing `site_url` alone never drops
|
|
92
|
+
`allowed_origins` or the rest of the pool a plain `put_pool` would otherwise
|
|
93
|
+
need restated in full.
|
|
94
|
+
|
|
95
|
+
The write is conditional: `update_pool` sends the `revision` its read returned as
|
|
96
|
+
`If-Match`, so if another administrator (Studio, a second script) changed the pool
|
|
97
|
+
in between, the server answers `409 pool_changed` and `update_pool` raises
|
|
98
|
+
`LyhnidosError` rather than overwriting their change; read again and retry.
|
|
99
|
+
`put_pool(pool)` stays unconditional (last writer wins) unless you pass
|
|
100
|
+
`if_match=<revision from get_pool()>`. Against a server that does not report a
|
|
101
|
+
`revision` (older than 0.6.13) both are last-writer-wins.
|
|
102
|
+
|
|
103
|
+
## License
|
|
104
|
+
|
|
105
|
+
MIT OR Apache-2.0
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Lyhnidos Geo Python Client
|
|
3
|
+
Native open data discovery, Apache Arrow binary transport, Ibis lazy DataFrame execution, and DuckDB analytics.
|
|
4
|
+
Also includes an admin SDK for the app platform (`lyhnidos.apps`): the
|
|
5
|
+
app-user pool, publishable keys, app users and their sessions, usage, and
|
|
6
|
+
row rules.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from .connector import (
|
|
10
|
+
LyhnidosClient,
|
|
11
|
+
connect_ibis,
|
|
12
|
+
connect_duckdb,
|
|
13
|
+
fetch_arrow,
|
|
14
|
+
get_openmetadata_catalog,
|
|
15
|
+
)
|
|
16
|
+
from .apps import AppsAdmin, LyhnidosError
|
|
17
|
+
|
|
18
|
+
__version__ = "0.2.0"
|
|
19
|
+
__all__ = [
|
|
20
|
+
"LyhnidosClient",
|
|
21
|
+
"connect_ibis",
|
|
22
|
+
"connect_duckdb",
|
|
23
|
+
"fetch_arrow",
|
|
24
|
+
"get_openmetadata_catalog",
|
|
25
|
+
"AppsAdmin",
|
|
26
|
+
"LyhnidosError",
|
|
27
|
+
]
|
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Lyhnidos Geo — app platform admin SDK (`lyhnidos.apps`)
|
|
3
|
+
|
|
4
|
+
A thin client for a workspace's own administration of its app platform: the
|
|
5
|
+
app-user pool, its signing keys, publishable keys, app users and their
|
|
6
|
+
sessions, usage, and row rules. Every method here is a direct call onto one
|
|
7
|
+
of the engine's `/v1/tenants/{id}/...` admin routes (see
|
|
8
|
+
`crates/lyhnidos-server/src/app_auth/admin.rs` and
|
|
9
|
+
`crates/lyhnidos-server/src/app_rules/admin.rs`); nothing here talks to an
|
|
10
|
+
app's own `/v1/apps/{workspace}/...` surface, which is a different audience
|
|
11
|
+
(end users, not the workspace administering them).
|
|
12
|
+
|
|
13
|
+
Depends only on `requests` (already a dependency of this package) and the
|
|
14
|
+
standard library -- deliberately kept separate from `lyhnidos.connector`,
|
|
15
|
+
which this module does not import and does not change.
|
|
16
|
+
|
|
17
|
+
from lyhnidos import AppsAdmin
|
|
18
|
+
|
|
19
|
+
admin = AppsAdmin("https://api.lyhnidos.dev", api_key, "acme")
|
|
20
|
+
admin.create_publishable_key("Marketing site")
|
|
21
|
+
admin.invite_user("new-user@example.com", role="member")
|
|
22
|
+
admin.put_table_rules("acme_main", "notes", enabled=True, rules=[
|
|
23
|
+
{"role": "*", "operation": "read", "preset": {"kind": "own_rows"}},
|
|
24
|
+
])
|
|
25
|
+
|
|
26
|
+
Every method returns the endpoint's parsed JSON body (a `dict`, or `None` for
|
|
27
|
+
a `204 No Content` answer -- none of the routes below actually send one today,
|
|
28
|
+
but the response handling honours it uniformly rather than assuming every
|
|
29
|
+
2xx carries a body). A non-2xx answer raises `LyhnidosError`; a network
|
|
30
|
+
failure (a connection refused, a timeout, ...) propagates as whatever
|
|
31
|
+
`requests` exception describes it -- this SDK never swallows one.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
from __future__ import annotations
|
|
35
|
+
|
|
36
|
+
from typing import Any, Dict, List, Optional
|
|
37
|
+
from urllib.parse import quote
|
|
38
|
+
|
|
39
|
+
import requests
|
|
40
|
+
|
|
41
|
+
# Kept in lockstep with `lyhnidos.__version__` by hand (not imported from
|
|
42
|
+
# there) so importing this module never depends on the parent package's
|
|
43
|
+
# `__init__` having finished running -- `lyhnidos/__init__.py` itself imports
|
|
44
|
+
# names from this module, and a module-level `from . import __version__`
|
|
45
|
+
# here would be a circular import at exactly that point.
|
|
46
|
+
_SDK_VERSION = "0.2.0"
|
|
47
|
+
USER_AGENT = f"lyhnidos-python/{_SDK_VERSION}"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class LyhnidosError(Exception):
|
|
51
|
+
"""A non-2xx answer from a Lyhnidos admin API call.
|
|
52
|
+
|
|
53
|
+
`status` is the HTTP status code. `code` is the string in `body["error"]`
|
|
54
|
+
when the body parsed as a JSON object with one, and `None` otherwise (a
|
|
55
|
+
non-JSON body, or a JSON body with no `error` field). `body` is the
|
|
56
|
+
response body: parsed JSON when the response was JSON, the raw text
|
|
57
|
+
otherwise.
|
|
58
|
+
|
|
59
|
+
Deliberately holds nothing about the request that produced it -- no
|
|
60
|
+
headers, no API key -- so neither `str()` nor `repr()` of an instance can
|
|
61
|
+
ever print a credential.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
def __init__(self, status: int, code: Optional[str], body: Any):
|
|
65
|
+
self.status = status
|
|
66
|
+
self.code = code
|
|
67
|
+
self.body = body
|
|
68
|
+
super().__init__(f"lyhnidos admin API request failed: status={status} code={code!r}")
|
|
69
|
+
|
|
70
|
+
def __repr__(self) -> str:
|
|
71
|
+
return f"LyhnidosError(status={self.status!r}, code={self.code!r}, body={self.body!r})"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class AppsAdmin:
|
|
75
|
+
"""A workspace's admin API for its app platform.
|
|
76
|
+
|
|
77
|
+
`base_url` is the installation's API origin (for example
|
|
78
|
+
`https://api.lyhnidos.dev`); `api_key` is a workspace-scoped admin key or
|
|
79
|
+
a fleet key; `workspace` is the tenant id every route here is scoped
|
|
80
|
+
under. `session` is injectable (a `requests.Session`-alike exposing
|
|
81
|
+
`.request(method, url, *, json=None, params=None, headers=None,
|
|
82
|
+
timeout=None)`) so tests can pass a fake that never touches the network;
|
|
83
|
+
it defaults to a fresh `requests.Session()`.
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
def __init__(
|
|
87
|
+
self,
|
|
88
|
+
base_url: str,
|
|
89
|
+
api_key: str,
|
|
90
|
+
workspace: str,
|
|
91
|
+
*,
|
|
92
|
+
timeout: float = 30,
|
|
93
|
+
session: Optional[Any] = None,
|
|
94
|
+
):
|
|
95
|
+
self.base_url = base_url.rstrip("/")
|
|
96
|
+
self.workspace = workspace
|
|
97
|
+
self.timeout = timeout
|
|
98
|
+
self.session = session if session is not None else requests.Session()
|
|
99
|
+
self._api_key = api_key
|
|
100
|
+
|
|
101
|
+
def __repr__(self) -> str:
|
|
102
|
+
# Never the API key: this is the one place a stray print/log/traceback
|
|
103
|
+
# of an AppsAdmin instance would otherwise leak it.
|
|
104
|
+
return f"AppsAdmin(base_url={self.base_url!r}, workspace={self.workspace!r})"
|
|
105
|
+
|
|
106
|
+
# ── Plumbing ──────────────────────────────────────────────
|
|
107
|
+
|
|
108
|
+
def _url(self, *segments: str) -> str:
|
|
109
|
+
"""`{base_url}/v1/tenants/{workspace}/<segments...>`, every segment
|
|
110
|
+
percent-encoded on its own (`urllib.parse.quote(seg, safe='')`) so a
|
|
111
|
+
value containing `/` -- a user id, in principle -- is carried as one
|
|
112
|
+
path segment rather than reinterpreted as more of them."""
|
|
113
|
+
path = "/".join(quote(str(segment), safe="") for segment in ("v1", "tenants", self.workspace, *segments))
|
|
114
|
+
return f"{self.base_url}/{path}"
|
|
115
|
+
|
|
116
|
+
def _headers(self) -> Dict[str, str]:
|
|
117
|
+
return {
|
|
118
|
+
"Authorization": f"Bearer {self._api_key}",
|
|
119
|
+
"User-Agent": USER_AGENT,
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
def _request(
|
|
123
|
+
self,
|
|
124
|
+
method: str,
|
|
125
|
+
url: str,
|
|
126
|
+
*,
|
|
127
|
+
json: Optional[Any] = None,
|
|
128
|
+
params: Optional[Dict[str, Any]] = None,
|
|
129
|
+
headers: Optional[Dict[str, str]] = None,
|
|
130
|
+
) -> Optional[Any]:
|
|
131
|
+
response = self.session.request(
|
|
132
|
+
method,
|
|
133
|
+
url,
|
|
134
|
+
json=json,
|
|
135
|
+
params=params,
|
|
136
|
+
headers={**self._headers(), **(headers or {})},
|
|
137
|
+
timeout=self.timeout,
|
|
138
|
+
)
|
|
139
|
+
if response.status_code == 204:
|
|
140
|
+
return None
|
|
141
|
+
try:
|
|
142
|
+
body = response.json()
|
|
143
|
+
except ValueError:
|
|
144
|
+
body = response.text
|
|
145
|
+
if not (200 <= response.status_code < 300):
|
|
146
|
+
code = body.get("error") if isinstance(body, dict) else None
|
|
147
|
+
raise LyhnidosError(response.status_code, code, self._scrub(body))
|
|
148
|
+
return body
|
|
149
|
+
|
|
150
|
+
def _scrub(self, value: Any) -> Any:
|
|
151
|
+
"""`value` with this client's API key replaced by `[redacted]`, so a
|
|
152
|
+
server (or proxy) that echoes a credential back in an error body can
|
|
153
|
+
never put it into an exception's `str()`, `repr()` or `.body`."""
|
|
154
|
+
if isinstance(value, str):
|
|
155
|
+
return value.replace(self._api_key, "[redacted]") if self._api_key else value
|
|
156
|
+
if isinstance(value, dict):
|
|
157
|
+
return {key: self._scrub(item) for key, item in value.items()}
|
|
158
|
+
if isinstance(value, list):
|
|
159
|
+
return [self._scrub(item) for item in value]
|
|
160
|
+
return value
|
|
161
|
+
|
|
162
|
+
# ── App pool & signing keys ───────────────────────────────
|
|
163
|
+
|
|
164
|
+
def get_pool(self) -> Optional[dict]:
|
|
165
|
+
"""`GET .../app-pool` -> `{"pool": {...}, "issuer": ..., "jwks_uri": ..., "publishable_key_header": ...}`."""
|
|
166
|
+
return self._request("GET", self._url("app-pool"))
|
|
167
|
+
|
|
168
|
+
def put_pool(self, pool: dict, *, if_match: Optional[str] = None) -> Optional[dict]:
|
|
169
|
+
"""`PUT .../app-pool` with the whole pool object -> `{"pool": {...}}`.
|
|
170
|
+
|
|
171
|
+
A field left out of `pool` takes its engine-side default (see
|
|
172
|
+
`AppPool` in `app_auth/mod.rs`) -- this is a replace, not a merge. Use
|
|
173
|
+
`update_pool` to change a few fields without restating the rest.
|
|
174
|
+
|
|
175
|
+
Unconditional (last writer wins) unless `if_match` is given: pass the
|
|
176
|
+
`revision` a `get_pool()` returned and the server answers
|
|
177
|
+
`409 pool_changed` if the pool changed since that read.
|
|
178
|
+
"""
|
|
179
|
+
headers = {"If-Match": if_match} if if_match else None
|
|
180
|
+
return self._request("PUT", self._url("app-pool"), json=pool, headers=headers)
|
|
181
|
+
|
|
182
|
+
def update_pool(self, **changes: Any) -> Optional[dict]:
|
|
183
|
+
"""Read the current pool, merge `changes` into its top-level fields,
|
|
184
|
+
and `PUT` the result -- so a caller changing `site_url` never has to
|
|
185
|
+
restate `allowed_origins`, `roles`, and everything else it did not
|
|
186
|
+
mean to touch.
|
|
187
|
+
|
|
188
|
+
The write is conditional: it carries the `revision` the read returned
|
|
189
|
+
as `If-Match`, so if another administrator (Studio, a second script)
|
|
190
|
+
changed the pool in between, the server answers `409 pool_changed` and
|
|
191
|
+
this raises `LyhnidosError` instead of silently overwriting their
|
|
192
|
+
change. Re-read and retry. Against an older server that reports no
|
|
193
|
+
`revision` the `PUT` is unconditional (last writer wins), as it always
|
|
194
|
+
was.
|
|
195
|
+
"""
|
|
196
|
+
current = self.get_pool()
|
|
197
|
+
pool = current.get("pool") if isinstance(current, dict) else None
|
|
198
|
+
if not isinstance(pool, dict):
|
|
199
|
+
# PUT replaces the whole pool: sending only `changes` would reset
|
|
200
|
+
# every other field to its default, switching app sign-in off.
|
|
201
|
+
raise LyhnidosError(0, "unexpected_pool_response", current)
|
|
202
|
+
revision = current.get("revision")
|
|
203
|
+
return self.put_pool(
|
|
204
|
+
{**pool, **changes},
|
|
205
|
+
if_match=revision if isinstance(revision, str) else None,
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
def rotate_signing_key(self) -> Optional[dict]:
|
|
209
|
+
"""`POST .../app-pool/signing-keys/rotate` -> `{"kid": "..."}`."""
|
|
210
|
+
return self._request("POST", self._url("app-pool", "signing-keys", "rotate"))
|
|
211
|
+
|
|
212
|
+
# ── Publishable keys ──────────────────────────────────────
|
|
213
|
+
|
|
214
|
+
def list_publishable_keys(self) -> Optional[dict]:
|
|
215
|
+
"""`GET .../publishable-keys` -> `{"keys": [{"key_prefix", "name", "created_at", "last_used_at"}, ...]}`."""
|
|
216
|
+
return self._request("GET", self._url("publishable-keys"))
|
|
217
|
+
|
|
218
|
+
def create_publishable_key(self, name: str) -> Optional[dict]:
|
|
219
|
+
"""`POST .../publishable-keys` -> the raw key, shown once:
|
|
220
|
+
`{"key", "key_prefix", "name", "created_at", "note"}`."""
|
|
221
|
+
return self._request("POST", self._url("publishable-keys"), json={"name": name})
|
|
222
|
+
|
|
223
|
+
def revoke_publishable_key(self, prefix: str) -> Optional[dict]:
|
|
224
|
+
"""`DELETE .../publishable-keys/{prefix}` -> `{"status": "revoked"}`."""
|
|
225
|
+
return self._request("DELETE", self._url("publishable-keys", prefix))
|
|
226
|
+
|
|
227
|
+
# ── Usage ─────────────────────────────────────────────────
|
|
228
|
+
|
|
229
|
+
def usage(self) -> Optional[dict]:
|
|
230
|
+
"""`GET .../app-usage` -> `{"month", "tier", "active_users", "included", "ceiling", "users"}`."""
|
|
231
|
+
return self._request("GET", self._url("app-usage"))
|
|
232
|
+
|
|
233
|
+
# ── App users ─────────────────────────────────────────────
|
|
234
|
+
|
|
235
|
+
def list_users(self, **params: Any) -> Optional[dict]:
|
|
236
|
+
"""`GET .../app-users?search=&offset=&limit=` -> `{"users": [...], "total": N}`.
|
|
237
|
+
|
|
238
|
+
`params` is passed straight through as the query string (`search`,
|
|
239
|
+
`offset`, `limit`) -- the same three the engine's `ListQuery` reads.
|
|
240
|
+
"""
|
|
241
|
+
return self._request("GET", self._url("app-users"), params=params)
|
|
242
|
+
|
|
243
|
+
def invite_user(self, email: str, **fields: Any) -> Optional[dict]:
|
|
244
|
+
"""`POST .../app-users` (invite) -> the created user, `201`.
|
|
245
|
+
|
|
246
|
+
`fields` may include `role`; left out, the pool's own default role is
|
|
247
|
+
used. Answers `409 already_a_user` (with `user_id`) when the address
|
|
248
|
+
already belongs to a user of this workspace.
|
|
249
|
+
"""
|
|
250
|
+
return self._request("POST", self._url("app-users"), json={"email": email, **fields})
|
|
251
|
+
|
|
252
|
+
def get_user(self, user_id: str) -> Optional[dict]:
|
|
253
|
+
"""`GET .../app-users/{user_id}`."""
|
|
254
|
+
return self._request("GET", self._url("app-users", user_id))
|
|
255
|
+
|
|
256
|
+
def update_user(self, user_id: str, **fields: Any) -> Optional[dict]:
|
|
257
|
+
"""`PATCH .../app-users/{user_id}`.
|
|
258
|
+
|
|
259
|
+
`fields` may include `role`, `display_name`, `claims`, `area`
|
|
260
|
+
(GeoJSON, `{"database", "table", "feature_id"}`, or `None` to clear)
|
|
261
|
+
and `disabled`. Disabling a user revokes every session of theirs at
|
|
262
|
+
once.
|
|
263
|
+
"""
|
|
264
|
+
return self._request("PATCH", self._url("app-users", user_id), json=fields)
|
|
265
|
+
|
|
266
|
+
def delete_user(self, user_id: str) -> Optional[dict]:
|
|
267
|
+
"""`DELETE .../app-users/{user_id}` -> `{"status": "deleted"}`."""
|
|
268
|
+
return self._request("DELETE", self._url("app-users", user_id))
|
|
269
|
+
|
|
270
|
+
def list_user_sessions(self, user_id: str) -> Optional[dict]:
|
|
271
|
+
"""`GET .../app-users/{user_id}/sessions` -> `{"sessions": [...]}`."""
|
|
272
|
+
return self._request("GET", self._url("app-users", user_id, "sessions"))
|
|
273
|
+
|
|
274
|
+
def revoke_user_sessions(self, user_id: str) -> Optional[dict]:
|
|
275
|
+
"""`DELETE .../app-users/{user_id}/sessions` -> `{"revoked": N}`."""
|
|
276
|
+
return self._request("DELETE", self._url("app-users", user_id, "sessions"))
|
|
277
|
+
|
|
278
|
+
# ── Row rules ─────────────────────────────────────────────
|
|
279
|
+
|
|
280
|
+
def get_rules(self, database: str) -> Optional[dict]:
|
|
281
|
+
"""`GET .../app-rules/{database}` -> `{"database", "is_public", "tables": [...]}`,
|
|
282
|
+
one entry per table the GIS surface lists, each with its columns,
|
|
283
|
+
whether apps may reach it, and its stored rules."""
|
|
284
|
+
return self._request("GET", self._url("app-rules", database))
|
|
285
|
+
|
|
286
|
+
def put_table_rules(
|
|
287
|
+
self,
|
|
288
|
+
database: str,
|
|
289
|
+
table: str,
|
|
290
|
+
*,
|
|
291
|
+
enabled: bool,
|
|
292
|
+
rules: List[dict],
|
|
293
|
+
) -> Optional[dict]:
|
|
294
|
+
"""`PUT .../app-rules/{database}/tables/{table}` -- replace one
|
|
295
|
+
table's whole rule set -> `{"table", "enabled", "added_created_by", "rules"}`.
|
|
296
|
+
|
|
297
|
+
Each entry of `rules` is `{"role", "operation", "preset"|"condition", "check"?}`
|
|
298
|
+
(see `RuleInput`/`Rule` in `app_rules/admin.rs`); an invalid one
|
|
299
|
+
answers `400 invalid_rule` with `index` and `reason`, and nothing is
|
|
300
|
+
saved.
|
|
301
|
+
"""
|
|
302
|
+
return self._request(
|
|
303
|
+
"PUT",
|
|
304
|
+
self._url("app-rules", database, "tables", table),
|
|
305
|
+
json={"enabled": enabled, "rules": rules},
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
def test_rules(self, database: str, *, subject: Any = None, **body: Any) -> Optional[dict]:
|
|
309
|
+
"""`POST .../app-rules/{database}/test` -- the rows one user (or
|
|
310
|
+
`anon`) would get from one table, enforced exactly as a real request
|
|
311
|
+
of theirs would be.
|
|
312
|
+
|
|
313
|
+
Who to test as is `subject`, sent as the engine's field `as` (a Python
|
|
314
|
+
keyword, so it cannot be a keyword argument itself):
|
|
315
|
+
|
|
316
|
+
admin.test_rules("acme_main", subject="anon", table="notes")
|
|
317
|
+
admin.test_rules("acme_main", subject={"user_id": "appu_1"}, table="notes", limit=10)
|
|
318
|
+
"""
|
|
319
|
+
if subject is not None:
|
|
320
|
+
body = {"as": subject, **body}
|
|
321
|
+
return self._request("POST", self._url("app-rules", database, "test"), json=body)
|