kraph 7.2.0__tar.gz → 8.0.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.
- {kraph-7.2.0 → kraph-8.0.0}/PKG-INFO +8 -8
- {kraph-7.2.0 → kraph-8.0.0}/README.md +6 -6
- kraph-8.0.0/kraph/__init__.py +6 -0
- kraph-8.0.0/kraph/_tested.json +1 -0
- kraph-8.0.0/kraph/connect.py +46 -0
- {kraph-7.2.0 → kraph-8.0.0}/kraph/datalayer.py +11 -4
- {kraph-7.2.0 → kraph-8.0.0}/kraph/io/download.py +27 -6
- {kraph-7.2.0 → kraph-8.0.0}/kraph/io/obstore.py +20 -6
- {kraph-7.2.0 → kraph-8.0.0}/kraph/io/upload.py +30 -8
- {kraph-7.2.0 → kraph-8.0.0}/kraph/kraph.py +47 -6
- {kraph-7.2.0 → kraph-8.0.0}/kraph/links/upload.py +0 -1
- {kraph-7.2.0 → kraph-8.0.0}/kraph/middleware/base.py +3 -3
- {kraph-7.2.0 → kraph-8.0.0}/kraph/middleware/upload.py +63 -15
- {kraph-7.2.0 → kraph-8.0.0}/kraph/pairs.py +25 -7
- {kraph-7.2.0 → kraph-8.0.0}/kraph/rath.py +9 -5
- {kraph-7.2.0 → kraph-8.0.0}/kraph/refs.py +1 -1
- {kraph-7.2.0 → kraph-8.0.0}/kraph/scalars.py +12 -4
- kraph-7.2.0/kraph/arkitekt.py → kraph-8.0.0/kraph/structures.py +40 -104
- {kraph-7.2.0 → kraph-8.0.0}/kraph/traits.py +93 -25
- {kraph-7.2.0 → kraph-8.0.0}/pyproject.toml +17 -59
- kraph-7.2.0/kraph/__init__.py +0 -7
- kraph-7.2.0/kraph/_tested.json +0 -1
- {kraph-7.2.0 → kraph-8.0.0}/.gitignore +0 -0
- {kraph-7.2.0 → kraph-8.0.0}/kraph/api/__init__.py +0 -0
- {kraph-7.2.0 → kraph-8.0.0}/kraph/api/project.json +0 -0
- {kraph-7.2.0 → kraph-8.0.0}/kraph/api/schema.graphql +0 -0
- {kraph-7.2.0 → kraph-8.0.0}/kraph/api/schema.py +0 -0
- {kraph-7.2.0 → kraph-8.0.0}/kraph/client.py +0 -0
- {kraph-7.2.0 → kraph-8.0.0}/kraph/contrib/fakts/__init__.py +0 -0
- {kraph-7.2.0 → kraph-8.0.0}/kraph/errors.py +0 -0
- {kraph-7.2.0 → kraph-8.0.0}/kraph/io/__init__.py +0 -0
- {kraph-7.2.0 → kraph-8.0.0}/kraph/links/__init__.py +0 -0
- {kraph-7.2.0 → kraph-8.0.0}/kraph/links/errors.py +0 -0
- {kraph-7.2.0 → kraph-8.0.0}/kraph/middleware/__init__.py +0 -0
- {kraph-7.2.0 → kraph-8.0.0}/kraph/py.typed +0 -0
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: kraph
|
|
3
|
-
Version:
|
|
3
|
+
Version: 8.0.0
|
|
4
4
|
Summary: the arkitekt knowledge graph
|
|
5
5
|
Author-email: jhnnsrs <jhnnsrs@gmail.com>
|
|
6
6
|
License-Expression: GPL-3.0-or-later
|
|
7
7
|
Requires-Python: <4.0,>=3.11
|
|
8
|
-
Requires-Dist: arkitekt-spec>=
|
|
8
|
+
Requires-Dist: arkitekt-spec>=14
|
|
9
9
|
Requires-Dist: dokker>=2.8
|
|
10
10
|
Requires-Dist: fakts>=6.1
|
|
11
11
|
Requires-Dist: obstore>=0.11.0
|
|
@@ -46,16 +46,16 @@ the client, so follow-ups from a result go through the same client.
|
|
|
46
46
|
|
|
47
47
|
### In an arkitekt app
|
|
48
48
|
|
|
49
|
-
|
|
49
|
+
Ask for `kraph: Kraph`; the client is injected by annotation.
|
|
50
50
|
Graphs, categories, structures, metrics, terms and more travel between actions by id
|
|
51
51
|
(`@kraph/graph`, `@kraph/entitycategory`, `@kraph/structure`, `@kraph/term`, …), so an action can
|
|
52
52
|
take and return them directly:
|
|
53
53
|
|
|
54
54
|
```python
|
|
55
55
|
from arkitekt import App, run
|
|
56
|
-
from kraph import Kraph
|
|
56
|
+
from kraph import Kraph
|
|
57
57
|
|
|
58
|
-
app = App("neuron-claims", "0.1.0"
|
|
58
|
+
app = App("neuron-claims", "0.1.0")
|
|
59
59
|
|
|
60
60
|
|
|
61
61
|
@app.action
|
|
@@ -77,10 +77,10 @@ if __name__ == "__main__":
|
|
|
77
77
|
### From a script
|
|
78
78
|
|
|
79
79
|
```python
|
|
80
|
-
from arkitekt import
|
|
81
|
-
from kraph import
|
|
80
|
+
from arkitekt import connect
|
|
81
|
+
from kraph import Kraph
|
|
82
82
|
|
|
83
|
-
with
|
|
83
|
+
with connect(Kraph) as kraph:
|
|
84
84
|
graph = kraph.create_graph(name="Neurons", backfill=False)
|
|
85
85
|
kraph.create_entity_category(
|
|
86
86
|
key="Neuron",
|
|
@@ -31,16 +31,16 @@ the client, so follow-ups from a result go through the same client.
|
|
|
31
31
|
|
|
32
32
|
### In an arkitekt app
|
|
33
33
|
|
|
34
|
-
|
|
34
|
+
Ask for `kraph: Kraph`; the client is injected by annotation.
|
|
35
35
|
Graphs, categories, structures, metrics, terms and more travel between actions by id
|
|
36
36
|
(`@kraph/graph`, `@kraph/entitycategory`, `@kraph/structure`, `@kraph/term`, …), so an action can
|
|
37
37
|
take and return them directly:
|
|
38
38
|
|
|
39
39
|
```python
|
|
40
40
|
from arkitekt import App, run
|
|
41
|
-
from kraph import Kraph
|
|
41
|
+
from kraph import Kraph
|
|
42
42
|
|
|
43
|
-
app = App("neuron-claims", "0.1.0"
|
|
43
|
+
app = App("neuron-claims", "0.1.0")
|
|
44
44
|
|
|
45
45
|
|
|
46
46
|
@app.action
|
|
@@ -62,10 +62,10 @@ if __name__ == "__main__":
|
|
|
62
62
|
### From a script
|
|
63
63
|
|
|
64
64
|
```python
|
|
65
|
-
from arkitekt import
|
|
66
|
-
from kraph import
|
|
65
|
+
from arkitekt import connect
|
|
66
|
+
from kraph import Kraph
|
|
67
67
|
|
|
68
|
-
with
|
|
68
|
+
with connect(Kraph) as kraph:
|
|
69
69
|
graph = kraph.create_graph(name="Neurons", backfill=False)
|
|
70
70
|
kraph.create_entity_category(
|
|
71
71
|
key="Neuron",
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version": "7.7.2"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""How ``Kraph`` reaches a resolved deployment: its links and upload middleware."""
|
|
2
|
+
|
|
3
|
+
from arkitekt_spec.declare.wiring import Alias, TokenLoader
|
|
4
|
+
from fakts.contrib.rath.auth import FaktsAuthLink
|
|
5
|
+
from rath.links import compose
|
|
6
|
+
from rath.links.aiohttp import AIOHttpLink
|
|
7
|
+
from rath.links.dictinglink import DictingLink
|
|
8
|
+
from rath.links.graphql_ws import GraphQLWSLink
|
|
9
|
+
from rath.links.shrink import ShrinkingLink
|
|
10
|
+
from rath.links.split import SplitLink
|
|
11
|
+
|
|
12
|
+
from graphql import OperationType
|
|
13
|
+
from kraph.datalayer import DataLayer
|
|
14
|
+
from kraph.links.upload import UploadLink
|
|
15
|
+
from kraph.middleware.upload import UploadMiddleware
|
|
16
|
+
from kraph.rath import KraphRath
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def kraph_rath(kraph: Alias, datalayer: DataLayer, tokens: TokenLoader) -> KraphRath:
|
|
20
|
+
"""The rath over http and ws, uploading files to ``datalayer`` first."""
|
|
21
|
+
return KraphRath(
|
|
22
|
+
# Files in a request (a model's weights) go to the datalayer first, as every service's do.
|
|
23
|
+
middlewares=[UploadMiddleware(datalayer=datalayer)],
|
|
24
|
+
link=compose(
|
|
25
|
+
ShrinkingLink(),
|
|
26
|
+
DictingLink(),
|
|
27
|
+
FaktsAuthLink(token_loader=tokens),
|
|
28
|
+
UploadLink(datalayer=datalayer),
|
|
29
|
+
SplitLink(
|
|
30
|
+
left=AIOHttpLink(
|
|
31
|
+
endpoint_url=kraph.to_http_path("graphql"),
|
|
32
|
+
proxy=kraph.proxy,
|
|
33
|
+
ssl_context=kraph.ssl_context(),
|
|
34
|
+
),
|
|
35
|
+
right=GraphQLWSLink(
|
|
36
|
+
ws_endpoint_url=kraph.to_ws_path("graphql"),
|
|
37
|
+
proxy=kraph.proxy,
|
|
38
|
+
ssl_context=kraph.ssl_context(),
|
|
39
|
+
),
|
|
40
|
+
split=lambda o: o.node.operation != OperationType.SUBSCRIPTION,
|
|
41
|
+
),
|
|
42
|
+
),
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
__all__ = ["kraph_rath"]
|
|
@@ -33,9 +33,13 @@ Example:
|
|
|
33
33
|
|
|
34
34
|
import ssl
|
|
35
35
|
from types import TracebackType
|
|
36
|
+
from typing import TypeVar
|
|
37
|
+
|
|
36
38
|
from fakts import Alias
|
|
37
39
|
from koil.composition import KoiledModel
|
|
38
40
|
|
|
41
|
+
_DataLayer = TypeVar("_DataLayer", bound="DataLayer")
|
|
42
|
+
|
|
39
43
|
|
|
40
44
|
class DataLayer(KoiledModel):
|
|
41
45
|
"""Implements a S3 DataLayer
|
|
@@ -67,8 +71,11 @@ class DataLayer(KoiledModel):
|
|
|
67
71
|
pinned, the public roots otherwise."""
|
|
68
72
|
from arkitekt_spec.declare import tls
|
|
69
73
|
|
|
70
|
-
return
|
|
71
|
-
|
|
74
|
+
return (
|
|
75
|
+
tls.pinned_context(self.certificates)
|
|
76
|
+
if self.certificates
|
|
77
|
+
else tls.default_context()
|
|
78
|
+
)
|
|
72
79
|
|
|
73
80
|
@classmethod
|
|
74
81
|
def from_alias(cls, alias: "Alias") -> "DataLayer":
|
|
@@ -88,10 +95,10 @@ class DataLayer(KoiledModel):
|
|
|
88
95
|
certificates=list(alias.certificates) if alias.is_pinned() else [],
|
|
89
96
|
)
|
|
90
97
|
|
|
91
|
-
async def get_endpoint_url(self):
|
|
98
|
+
async def get_endpoint_url(self) -> str:
|
|
92
99
|
return self.endpoint_url
|
|
93
100
|
|
|
94
|
-
async def __aenter__(self):
|
|
101
|
+
async def __aenter__(self: _DataLayer) -> _DataLayer:
|
|
95
102
|
"""Enter the DataLayer context.
|
|
96
103
|
|
|
97
104
|
Entering does not make it "the current datalayer", and kraph never looks one up: downloads go
|
|
@@ -4,6 +4,7 @@ Both clients are the ones the object was fetched with (``client_of``): the kraph
|
|
|
4
4
|
for the grant, and its datalayer, which says where the store is. Nothing is looked up.
|
|
5
5
|
"""
|
|
6
6
|
|
|
7
|
+
import asyncio
|
|
7
8
|
from pathlib import Path
|
|
8
9
|
from typing import TYPE_CHECKING, Any
|
|
9
10
|
|
|
@@ -24,8 +25,15 @@ def download_bigfile(store_id: str, file_name: str, kraph: "Kraph") -> str:
|
|
|
24
25
|
"""Stream the big file in ``store_id`` to ``file_name``. Returns the path written."""
|
|
25
26
|
from kraph.api.schema import RequestBigFileAccessInput
|
|
26
27
|
|
|
27
|
-
grant = kraph.request_bigfile_access(
|
|
28
|
-
|
|
28
|
+
grant = kraph.request_bigfile_access(
|
|
29
|
+
input=RequestBigFileAccessInput(store_id=store_id)
|
|
30
|
+
)
|
|
31
|
+
store = create_s3_store(
|
|
32
|
+
kraph.datalayer.endpoint_url,
|
|
33
|
+
grant,
|
|
34
|
+
proxy=kraph.datalayer.proxy,
|
|
35
|
+
certificates=kraph.datalayer.certificates,
|
|
36
|
+
)
|
|
29
37
|
response = obstore.get(store, grant.key)
|
|
30
38
|
with open(_target(file_name), "wb") as file:
|
|
31
39
|
for chunk in response.stream():
|
|
@@ -37,10 +45,19 @@ async def adownload_bigfile(store_id: str, file_name: str, kraph: "Kraph") -> st
|
|
|
37
45
|
"""Stream the big file in ``store_id`` to ``file_name``. Returns the path written."""
|
|
38
46
|
from kraph.api.schema import RequestBigFileAccessInput
|
|
39
47
|
|
|
40
|
-
grant = await kraph.arequest_bigfile_access(
|
|
41
|
-
|
|
48
|
+
grant = await kraph.arequest_bigfile_access(
|
|
49
|
+
input=RequestBigFileAccessInput(store_id=store_id)
|
|
50
|
+
)
|
|
51
|
+
store = create_s3_store(
|
|
52
|
+
await kraph.datalayer.get_endpoint_url(),
|
|
53
|
+
grant,
|
|
54
|
+
proxy=kraph.datalayer.proxy,
|
|
55
|
+
certificates=kraph.datalayer.certificates,
|
|
56
|
+
)
|
|
42
57
|
response = await obstore.get_async(store, grant.key)
|
|
43
|
-
|
|
58
|
+
# Opened off the loop; the writes are of chunks already in memory.
|
|
59
|
+
file = await asyncio.to_thread(open, _target(file_name), "wb")
|
|
60
|
+
with file:
|
|
44
61
|
async for chunk in response.stream():
|
|
45
62
|
file.write(chunk)
|
|
46
63
|
return file_name
|
|
@@ -48,4 +65,8 @@ async def adownload_bigfile(store_id: str, file_name: str, kraph: "Kraph") -> st
|
|
|
48
65
|
|
|
49
66
|
def file_name_of(store: Any, file_name: str | None) -> str: # noqa: ANN401
|
|
50
67
|
"""Where a download lands: the name asked for, else the uploaded file's own name, else its key's last part."""
|
|
51
|
-
return
|
|
68
|
+
return (
|
|
69
|
+
file_name
|
|
70
|
+
or getattr(store, "original_file_name", None)
|
|
71
|
+
or str(store.key).rsplit("/", 1)[-1]
|
|
72
|
+
)
|
|
@@ -40,7 +40,9 @@ class S3UploadGrantLike(Protocol):
|
|
|
40
40
|
#: Called with the store id; returns a new grant for the *same* key. A context variable rather
|
|
41
41
|
#: than a parameter because the store is built several calls down, in every writer the
|
|
42
42
|
#: middleware drives, and the refresher is the middleware's to know about.
|
|
43
|
-
upload_refresher: ContextVar["Callable[[str], S3UploadGrantLike] | None"] = ContextVar(
|
|
43
|
+
upload_refresher: ContextVar["Callable[[str], S3UploadGrantLike] | None"] = ContextVar(
|
|
44
|
+
"upload_refresher", default=None
|
|
45
|
+
)
|
|
44
46
|
|
|
45
47
|
#: How long before a grant runs out a fresh one is asked for. obstore asks its credential
|
|
46
48
|
#: provider again shortly before the expiry it reported; refreshing a little earlier than that
|
|
@@ -60,7 +62,9 @@ class RefreshingUploadCredentials:
|
|
|
60
62
|
refreshes would mint two sessions for nothing.
|
|
61
63
|
"""
|
|
62
64
|
|
|
63
|
-
def __init__(
|
|
65
|
+
def __init__(
|
|
66
|
+
self, grant: "S3UploadGrantLike", refresh: "Callable[[], S3UploadGrantLike]"
|
|
67
|
+
) -> None:
|
|
64
68
|
"""Wrap the grant an upload started with, and how to renew it."""
|
|
65
69
|
self._refresh = refresh
|
|
66
70
|
self._lock = threading.Lock()
|
|
@@ -69,13 +73,19 @@ class RefreshingUploadCredentials:
|
|
|
69
73
|
def _install(self, grant: "S3UploadGrantLike") -> None:
|
|
70
74
|
self._grant = grant
|
|
71
75
|
expires_in = getattr(grant, "expires_in", None)
|
|
72
|
-
self._expires_at =
|
|
76
|
+
self._expires_at = (
|
|
77
|
+
datetime.datetime.now(datetime.UTC) + datetime.timedelta(seconds=expires_in)
|
|
78
|
+
if expires_in
|
|
79
|
+
else None
|
|
80
|
+
)
|
|
73
81
|
|
|
74
82
|
def __call__(self) -> "S3Credential":
|
|
75
83
|
"""The credentials to sign the next request with."""
|
|
76
84
|
with self._lock:
|
|
77
85
|
if self._expires_at is not None:
|
|
78
|
-
remaining = (
|
|
86
|
+
remaining = (
|
|
87
|
+
self._expires_at - datetime.datetime.now(datetime.UTC)
|
|
88
|
+
).total_seconds()
|
|
79
89
|
if remaining < UPLOAD_REFRESH_MARGIN_SECONDS:
|
|
80
90
|
self._install(self._refresh())
|
|
81
91
|
return {
|
|
@@ -120,7 +130,9 @@ def create_s3_store(
|
|
|
120
130
|
if proxy:
|
|
121
131
|
normalized_client_options["proxy_url"] = proxy
|
|
122
132
|
if certificates:
|
|
123
|
-
normalized_client_options["root_certificate"] = "\n".join(
|
|
133
|
+
normalized_client_options["root_certificate"] = "\n".join(
|
|
134
|
+
pem.strip() for pem in certificates
|
|
135
|
+
)
|
|
124
136
|
normalized_client_options["disable_system_certificates"] = True
|
|
125
137
|
|
|
126
138
|
store_kwargs: dict[str, object] = {
|
|
@@ -133,7 +145,9 @@ def create_s3_store(
|
|
|
133
145
|
store_id = getattr(grant, "store", None)
|
|
134
146
|
if refresh is not None and store_id:
|
|
135
147
|
# Inside an upload: credentials that renew themselves against the same store.
|
|
136
|
-
store_kwargs["credential_provider"] = RefreshingUploadCredentials(
|
|
148
|
+
store_kwargs["credential_provider"] = RefreshingUploadCredentials(
|
|
149
|
+
grant, lambda: refresh(store_id)
|
|
150
|
+
)
|
|
137
151
|
else:
|
|
138
152
|
store_kwargs["access_key_id"] = grant.access_key
|
|
139
153
|
store_kwargs["secret_access_key"] = grant.secret_key
|
|
@@ -21,24 +21,46 @@ if TYPE_CHECKING:
|
|
|
21
21
|
logger = logging.getLogger(__name__)
|
|
22
22
|
|
|
23
23
|
|
|
24
|
-
def upload_bigfile(
|
|
24
|
+
def upload_bigfile(
|
|
25
|
+
file: BigFile, credentials: "BigFileUploadGrant", datalayer: "DataLayer"
|
|
26
|
+
) -> str:
|
|
25
27
|
"""Write ``file`` to the object its grant names, synchronously. Returns the store id."""
|
|
26
|
-
store = create_s3_store(
|
|
28
|
+
store = create_s3_store(
|
|
29
|
+
datalayer.endpoint_url,
|
|
30
|
+
credentials,
|
|
31
|
+
proxy=datalayer.proxy,
|
|
32
|
+
certificates=datalayer.certificates,
|
|
33
|
+
)
|
|
27
34
|
try:
|
|
28
35
|
obstore.put(store, credentials.key, file.value)
|
|
29
36
|
except Exception as e:
|
|
30
|
-
raise UploadError(
|
|
31
|
-
|
|
37
|
+
raise UploadError(
|
|
38
|
+
f"Error while uploading to s3://{credentials.bucket}/{credentials.key} on {datalayer.endpoint_url}"
|
|
39
|
+
) from e
|
|
40
|
+
logger.info(
|
|
41
|
+
"Uploaded %s to s3://%s/%s", file.file_name, credentials.bucket, credentials.key
|
|
42
|
+
)
|
|
32
43
|
return credentials.store
|
|
33
44
|
|
|
34
45
|
|
|
35
|
-
async def aupload_bigfile(
|
|
46
|
+
async def aupload_bigfile(
|
|
47
|
+
file: BigFile, credentials: "BigFileUploadGrant", datalayer: "DataLayer"
|
|
48
|
+
) -> str:
|
|
36
49
|
"""Write ``file`` to the object its grant names. Returns the store id."""
|
|
37
50
|
endpoint_url = await datalayer.get_endpoint_url()
|
|
38
|
-
store = create_s3_store(
|
|
51
|
+
store = create_s3_store(
|
|
52
|
+
endpoint_url,
|
|
53
|
+
credentials,
|
|
54
|
+
proxy=datalayer.proxy,
|
|
55
|
+
certificates=datalayer.certificates,
|
|
56
|
+
)
|
|
39
57
|
try:
|
|
40
58
|
await obstore.put_async(store, credentials.key, file.value)
|
|
41
59
|
except Exception as e:
|
|
42
|
-
raise UploadError(
|
|
43
|
-
|
|
60
|
+
raise UploadError(
|
|
61
|
+
f"Error while uploading to s3://{credentials.bucket}/{credentials.key} on {endpoint_url}"
|
|
62
|
+
) from e
|
|
63
|
+
logger.info(
|
|
64
|
+
"Uploaded %s to s3://%s/%s", file.file_name, credentials.bucket, credentials.key
|
|
65
|
+
)
|
|
44
66
|
return credentials.store
|
|
@@ -16,12 +16,15 @@ nullable field in this schema already defaults to null, so omitting and sending
|
|
|
16
16
|
same thing.
|
|
17
17
|
"""
|
|
18
18
|
|
|
19
|
+
import os
|
|
19
20
|
from collections.abc import AsyncGenerator, Generator
|
|
20
|
-
from typing import Any
|
|
21
|
+
from typing import Annotated, Any, Self
|
|
21
22
|
|
|
23
|
+
from arkitekt_spec.declare.client import client
|
|
24
|
+
from arkitekt_spec.declare.tested import tested_against
|
|
25
|
+
from arkitekt_spec.declare.wiring import Alias, Require, TokenLoader
|
|
22
26
|
from koil import unkoil, unkoil_gen
|
|
23
27
|
from koil.composition import Composition
|
|
24
|
-
from pydantic import Field
|
|
25
28
|
from rath.origin import origin_context
|
|
26
29
|
from rath.task import TASK_HEADER, TaskLike, current_task, token_of
|
|
27
30
|
from rath.turms.funcs import TOperation
|
|
@@ -30,9 +33,22 @@ from kraph.api.schema import KraphApi
|
|
|
30
33
|
from kraph.datalayer import DataLayer
|
|
31
34
|
from kraph.rath import KraphRath
|
|
32
35
|
|
|
36
|
+
TESTED = tested_against("kraph")
|
|
37
|
+
"""The kraph server this release wants: the one its release job tested it against."""
|
|
33
38
|
|
|
39
|
+
_API = os.path.join(os.path.dirname(__file__), "api")
|
|
40
|
+
KRAPH = Require(
|
|
41
|
+
"live.arkitekt.kraph",
|
|
42
|
+
"Where the knowledge graph relating entities lives",
|
|
43
|
+
version=TESTED,
|
|
44
|
+
)
|
|
45
|
+
S3 = Require("live.arkitekt.s3", "Where the graph's files are stored", optional=True)
|
|
34
46
|
|
|
35
47
|
|
|
48
|
+
@client(
|
|
49
|
+
schema=os.path.join(_API, "schema.graphql"),
|
|
50
|
+
turms=os.path.join(_API, "project.json"),
|
|
51
|
+
)
|
|
36
52
|
class Kraph(Composition, KraphApi):
|
|
37
53
|
"""The kraph client.
|
|
38
54
|
|
|
@@ -46,17 +62,42 @@ class Kraph(Composition, KraphApi):
|
|
|
46
62
|
rath: KraphRath
|
|
47
63
|
datalayer: DataLayer
|
|
48
64
|
|
|
65
|
+
@classmethod
|
|
66
|
+
def from_fakts(
|
|
67
|
+
cls,
|
|
68
|
+
kraph: Annotated[Alias, KRAPH],
|
|
69
|
+
datalayer: Annotated[Alias | None, S3],
|
|
70
|
+
tokens: TokenLoader,
|
|
71
|
+
) -> Self:
|
|
72
|
+
"""Kraph over the resolved deployment.
|
|
73
|
+
|
|
74
|
+
Without a store the client still works; only uploads do not.
|
|
75
|
+
"""
|
|
76
|
+
from kraph.connect import kraph_rath
|
|
77
|
+
|
|
78
|
+
store = (
|
|
79
|
+
DataLayer.from_alias(datalayer) if datalayer is not None else DataLayer()
|
|
80
|
+
)
|
|
81
|
+
return cls(rath=kraph_rath(kraph, store, tokens), datalayer=store)
|
|
49
82
|
|
|
50
83
|
@staticmethod
|
|
51
|
-
def _serialize(
|
|
84
|
+
def _serialize(
|
|
85
|
+
operation: type[TOperation], variables: dict[str, Any]
|
|
86
|
+
) -> dict[str, Any]:
|
|
52
87
|
# exclude_none, not exclude_unset: see the module docstring.
|
|
53
|
-
return operation.Arguments(**variables).model_dump(
|
|
88
|
+
return operation.Arguments(**variables).model_dump(
|
|
89
|
+
by_alias=True, exclude_none=True
|
|
90
|
+
)
|
|
54
91
|
|
|
55
|
-
async def _aprepare(
|
|
92
|
+
async def _aprepare(
|
|
93
|
+
self, operation: type[TOperation], variables: dict[str, Any]
|
|
94
|
+
) -> dict[str, Any]:
|
|
56
95
|
"""Serialize the variables, then run the rath's middlewares over them (uploads, in order)."""
|
|
57
96
|
serialized = self._serialize(operation, variables)
|
|
58
97
|
for middleware in self.rath.middlewares:
|
|
59
|
-
serialized = await middleware.aprocess_variables(
|
|
98
|
+
serialized = await middleware.aprocess_variables(
|
|
99
|
+
serialized, operation, self.rath
|
|
100
|
+
)
|
|
60
101
|
return serialized
|
|
61
102
|
|
|
62
103
|
def _origin(self) -> dict[str, Any]:
|
|
@@ -21,7 +21,6 @@ The class is kept — rather than deleted — because ``KraphLinkComposition.upl
|
|
|
21
21
|
field and ``tests/conftest.py`` imports the name. It passes operations through untouched.
|
|
22
22
|
"""
|
|
23
23
|
|
|
24
|
-
|
|
25
24
|
from pydantic import ConfigDict, Field
|
|
26
25
|
from rath.links.parsing import ParsingLink
|
|
27
26
|
from rath.operation import Operation
|
|
@@ -12,7 +12,7 @@ Both sync and async variants are supported:
|
|
|
12
12
|
from __future__ import annotations
|
|
13
13
|
|
|
14
14
|
import abc
|
|
15
|
-
from typing import
|
|
15
|
+
from typing import TYPE_CHECKING, Any
|
|
16
16
|
|
|
17
17
|
from pydantic import BaseModel
|
|
18
18
|
|
|
@@ -45,7 +45,7 @@ class OperationMiddleware(BaseModel, abc.ABC):
|
|
|
45
45
|
self,
|
|
46
46
|
variables: dict[str, Any],
|
|
47
47
|
operation: type[TOperation],
|
|
48
|
-
rath:
|
|
48
|
+
rath: KraphRath,
|
|
49
49
|
) -> dict[str, Any]:
|
|
50
50
|
"""Process the serialized variables dict synchronously.
|
|
51
51
|
|
|
@@ -67,7 +67,7 @@ class OperationMiddleware(BaseModel, abc.ABC):
|
|
|
67
67
|
self,
|
|
68
68
|
variables: dict[str, Any],
|
|
69
69
|
operation: type[TOperation],
|
|
70
|
-
rath:
|
|
70
|
+
rath: KraphRath,
|
|
71
71
|
) -> dict[str, Any]:
|
|
72
72
|
"""Process the serialized variables dict asynchronously.
|
|
73
73
|
|
|
@@ -48,7 +48,9 @@ async def _apply_async(func: Callable[[Any], Awaitable[Any]], obj: Any) -> Any:
|
|
|
48
48
|
if isinstance(obj, list):
|
|
49
49
|
return list(await asyncio.gather(*[_apply_async(func, value) for value in obj]))
|
|
50
50
|
if isinstance(obj, tuple):
|
|
51
|
-
return tuple(
|
|
51
|
+
return tuple(
|
|
52
|
+
await asyncio.gather(*[_apply_async(func, value) for value in obj])
|
|
53
|
+
)
|
|
52
54
|
if isinstance(obj, BigFile):
|
|
53
55
|
return await func(obj)
|
|
54
56
|
return obj
|
|
@@ -102,11 +104,19 @@ class UploadMiddleware(OperationMiddleware):
|
|
|
102
104
|
|
|
103
105
|
@staticmethod
|
|
104
106
|
def _request(file: BigFile) -> dict[str, Any]:
|
|
105
|
-
return _variables(
|
|
107
|
+
return _variables(
|
|
108
|
+
RequestBigfileUploadMutation,
|
|
109
|
+
RequestBigFileUploadInput(
|
|
110
|
+
original_file_name=file.file_name, file_size=_byte_size(file.value)
|
|
111
|
+
),
|
|
112
|
+
)
|
|
106
113
|
|
|
107
114
|
@staticmethod
|
|
108
115
|
def _finish(store_id: str, valid: bool) -> dict[str, Any]:
|
|
109
|
-
return _variables(
|
|
116
|
+
return _variables(
|
|
117
|
+
FinishBigfileUploadMutation,
|
|
118
|
+
FinishBigFileUploadInput(store_id=store_id, valid=valid),
|
|
119
|
+
)
|
|
110
120
|
|
|
111
121
|
def _refresher(self, rath: "KraphRath") -> Callable[[str], Any]:
|
|
112
122
|
"""How to renew the grant, callable from obstore's own worker threads.
|
|
@@ -118,52 +128,90 @@ class UploadMiddleware(OperationMiddleware):
|
|
|
118
128
|
captured = contextvars.copy_context()
|
|
119
129
|
|
|
120
130
|
def refresh(store_id: str) -> Any: # noqa: ANN401
|
|
121
|
-
variables = _variables(
|
|
122
|
-
|
|
131
|
+
variables = _variables(
|
|
132
|
+
RefreshBigfileUploadMutation, RefreshUploadInput(store_id=store_id)
|
|
133
|
+
)
|
|
134
|
+
result = captured.copy().run(
|
|
135
|
+
rath.query, RefreshBigfileUploadMutation.Meta.document, variables
|
|
136
|
+
)
|
|
123
137
|
return RefreshBigfileUploadMutation(**result.data).refresh_bigfile_upload
|
|
124
138
|
|
|
125
139
|
return refresh
|
|
126
140
|
|
|
127
141
|
def _upload(self, rath: "KraphRath", file: BigFile) -> str:
|
|
128
142
|
"""Grant, write with self-renewing credentials, finish; or report the failure and re-raise."""
|
|
129
|
-
grant = RequestBigfileUploadMutation(
|
|
143
|
+
grant = RequestBigfileUploadMutation(
|
|
144
|
+
**rath.query(
|
|
145
|
+
RequestBigfileUploadMutation.Meta.document, self._request(file)
|
|
146
|
+
).data
|
|
147
|
+
).request_bigfile_upload
|
|
130
148
|
token = upload_refresher.set(self._refresher(rath))
|
|
131
149
|
try:
|
|
132
150
|
store_id = upload_bigfile(file, grant, self.datalayer)
|
|
133
151
|
except BaseException:
|
|
134
152
|
try:
|
|
135
|
-
rath.query(
|
|
153
|
+
rath.query(
|
|
154
|
+
FinishBigfileUploadMutation.Meta.document,
|
|
155
|
+
self._finish(grant.store, valid=False),
|
|
156
|
+
)
|
|
136
157
|
except Exception: # noqa: BLE001 - the write's own error is the one to raise
|
|
137
|
-
logger.warning(
|
|
158
|
+
logger.warning(
|
|
159
|
+
"Could not report the failed upload of store %s; it is collected once its deadline passes.",
|
|
160
|
+
grant.store,
|
|
161
|
+
exc_info=True,
|
|
162
|
+
)
|
|
138
163
|
raise
|
|
139
164
|
finally:
|
|
140
165
|
upload_refresher.reset(token)
|
|
141
|
-
rath.query(
|
|
166
|
+
rath.query(
|
|
167
|
+
FinishBigfileUploadMutation.Meta.document,
|
|
168
|
+
self._finish(store_id, valid=True),
|
|
169
|
+
)
|
|
142
170
|
return store_id
|
|
143
171
|
|
|
144
172
|
async def _aupload(self, rath: "KraphRath", file: BigFile) -> str:
|
|
145
173
|
"""Grant, write with self-renewing credentials, finish; or report the failure and re-raise."""
|
|
146
|
-
grant = RequestBigfileUploadMutation(
|
|
174
|
+
grant = RequestBigfileUploadMutation(
|
|
175
|
+
**(
|
|
176
|
+
await rath.aquery(
|
|
177
|
+
RequestBigfileUploadMutation.Meta.document, self._request(file)
|
|
178
|
+
)
|
|
179
|
+
).data
|
|
180
|
+
).request_bigfile_upload
|
|
147
181
|
token = upload_refresher.set(self._refresher(rath))
|
|
148
182
|
try:
|
|
149
183
|
store_id = await aupload_bigfile(file, grant, self.datalayer)
|
|
150
184
|
except BaseException:
|
|
151
185
|
try:
|
|
152
|
-
await rath.aquery(
|
|
186
|
+
await rath.aquery(
|
|
187
|
+
FinishBigfileUploadMutation.Meta.document,
|
|
188
|
+
self._finish(grant.store, valid=False),
|
|
189
|
+
)
|
|
153
190
|
except Exception: # noqa: BLE001 - the write's own error is the one to raise
|
|
154
|
-
logger.warning(
|
|
191
|
+
logger.warning(
|
|
192
|
+
"Could not report the failed upload of store %s; it is collected once its deadline passes.",
|
|
193
|
+
grant.store,
|
|
194
|
+
exc_info=True,
|
|
195
|
+
)
|
|
155
196
|
raise
|
|
156
197
|
finally:
|
|
157
198
|
upload_refresher.reset(token)
|
|
158
|
-
await rath.aquery(
|
|
199
|
+
await rath.aquery(
|
|
200
|
+
FinishBigfileUploadMutation.Meta.document,
|
|
201
|
+
self._finish(store_id, valid=True),
|
|
202
|
+
)
|
|
159
203
|
return store_id
|
|
160
204
|
|
|
161
205
|
# --- the middleware ----------------------------------------------------------------
|
|
162
206
|
|
|
163
|
-
def process_variables(
|
|
207
|
+
def process_variables(
|
|
208
|
+
self, variables: dict[str, Any], operation: type[TOperation], rath: "KraphRath"
|
|
209
|
+
) -> dict[str, Any]:
|
|
164
210
|
"""Upload every ``BigFile`` in ``variables`` and put its store id in its place."""
|
|
165
211
|
return _apply_sync(partial(self._upload, rath), variables)
|
|
166
212
|
|
|
167
|
-
async def aprocess_variables(
|
|
213
|
+
async def aprocess_variables(
|
|
214
|
+
self, variables: dict[str, Any], operation: type[TOperation], rath: "KraphRath"
|
|
215
|
+
) -> dict[str, Any]:
|
|
168
216
|
"""Upload every ``BigFile`` in ``variables`` and put its store id in its place."""
|
|
169
217
|
return await _apply_async(partial(self._aupload, rath), variables)
|