kraph 7.2.0__tar.gz → 7.2.1__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-7.2.1}/PKG-INFO +1 -1
- {kraph-7.2.0 → kraph-7.2.1}/kraph/__init__.py +1 -3
- kraph-7.2.1/kraph/_tested.json +1 -0
- {kraph-7.2.0 → kraph-7.2.1}/kraph/arkitekt.py +57 -26
- {kraph-7.2.0 → kraph-7.2.1}/kraph/datalayer.py +11 -4
- {kraph-7.2.0 → kraph-7.2.1}/kraph/io/download.py +27 -6
- {kraph-7.2.0 → kraph-7.2.1}/kraph/io/obstore.py +20 -6
- {kraph-7.2.0 → kraph-7.2.1}/kraph/io/upload.py +30 -8
- {kraph-7.2.0 → kraph-7.2.1}/kraph/kraph.py +12 -8
- {kraph-7.2.0 → kraph-7.2.1}/kraph/links/upload.py +0 -1
- {kraph-7.2.0 → kraph-7.2.1}/kraph/middleware/base.py +3 -3
- {kraph-7.2.0 → kraph-7.2.1}/kraph/middleware/upload.py +63 -15
- {kraph-7.2.0 → kraph-7.2.1}/kraph/pairs.py +25 -7
- {kraph-7.2.0 → kraph-7.2.1}/kraph/rath.py +9 -5
- {kraph-7.2.0 → kraph-7.2.1}/kraph/refs.py +1 -1
- {kraph-7.2.0 → kraph-7.2.1}/kraph/scalars.py +12 -4
- {kraph-7.2.0 → kraph-7.2.1}/kraph/traits.py +93 -25
- {kraph-7.2.0 → kraph-7.2.1}/pyproject.toml +6 -42
- kraph-7.2.0/kraph/_tested.json +0 -1
- {kraph-7.2.0 → kraph-7.2.1}/.gitignore +0 -0
- {kraph-7.2.0 → kraph-7.2.1}/README.md +0 -0
- {kraph-7.2.0 → kraph-7.2.1}/kraph/api/__init__.py +0 -0
- {kraph-7.2.0 → kraph-7.2.1}/kraph/api/project.json +0 -0
- {kraph-7.2.0 → kraph-7.2.1}/kraph/api/schema.graphql +0 -0
- {kraph-7.2.0 → kraph-7.2.1}/kraph/api/schema.py +0 -0
- {kraph-7.2.0 → kraph-7.2.1}/kraph/client.py +0 -0
- {kraph-7.2.0 → kraph-7.2.1}/kraph/contrib/fakts/__init__.py +0 -0
- {kraph-7.2.0 → kraph-7.2.1}/kraph/errors.py +0 -0
- {kraph-7.2.0 → kraph-7.2.1}/kraph/io/__init__.py +0 -0
- {kraph-7.2.0 → kraph-7.2.1}/kraph/links/__init__.py +0 -0
- {kraph-7.2.0 → kraph-7.2.1}/kraph/links/errors.py +0 -0
- {kraph-7.2.0 → kraph-7.2.1}/kraph/middleware/__init__.py +0 -0
- {kraph-7.2.0 → kraph-7.2.1}/kraph/py.typed +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version": "7.7.1"}
|
|
@@ -25,9 +25,11 @@ table-query surface.
|
|
|
25
25
|
import os
|
|
26
26
|
from typing import Annotated
|
|
27
27
|
|
|
28
|
+
from arkitekt_spec.declare.app import AppRegistry
|
|
29
|
+
from arkitekt_spec.declare.tested import tested_against
|
|
30
|
+
from arkitekt_spec.declare.widgets import SearchWidget
|
|
28
31
|
from fakts import Alias, Require, TokenLoader
|
|
29
32
|
from fakts.contrib.rath.auth import FaktsAuthLink
|
|
30
|
-
from graphql import OperationType
|
|
31
33
|
from rath.links import compose
|
|
32
34
|
from rath.links.aiohttp import AIOHttpLink
|
|
33
35
|
from rath.links.dictinglink import DictingLink
|
|
@@ -35,13 +37,11 @@ from rath.links.graphql_ws import GraphQLWSLink
|
|
|
35
37
|
from rath.links.shrink import ShrinkingLink
|
|
36
38
|
from rath.links.split import SplitLink
|
|
37
39
|
|
|
38
|
-
from
|
|
39
|
-
from arkitekt_spec.declare.tested import tested_against
|
|
40
|
-
from arkitekt_spec.declare.widgets import SearchWidget
|
|
41
|
-
|
|
40
|
+
from graphql import OperationType
|
|
42
41
|
from kraph.api.schema import (
|
|
43
42
|
EntityCategory,
|
|
44
43
|
Graph,
|
|
44
|
+
GraphPairsQuery,
|
|
45
45
|
Instance,
|
|
46
46
|
Link,
|
|
47
47
|
MeasurementCategory,
|
|
@@ -49,17 +49,16 @@ from kraph.api.schema import (
|
|
|
49
49
|
MetricKind,
|
|
50
50
|
Model,
|
|
51
51
|
NaturalEventCategory,
|
|
52
|
-
GraphPairsQuery,
|
|
53
52
|
PairsQueryRun,
|
|
54
53
|
ProtocolEventCategory,
|
|
55
54
|
RelationCategory,
|
|
56
55
|
SearchEntityCategoriesQuery,
|
|
56
|
+
SearchGraphPairsQueriesQuery,
|
|
57
57
|
SearchGraphsQuery,
|
|
58
58
|
SearchMeasurementCategoriesQuery,
|
|
59
59
|
SearchMetricKindsQuery,
|
|
60
60
|
SearchModelsQuery,
|
|
61
61
|
SearchNaturalEventCategoriesQuery,
|
|
62
|
-
SearchGraphPairsQueriesQuery,
|
|
63
62
|
SearchPairsQueryRunsQuery,
|
|
64
63
|
SearchProtocolEventCategoriesQuery,
|
|
65
64
|
SearchRelationCategoriesQuery,
|
|
@@ -72,7 +71,6 @@ from kraph.api.schema import (
|
|
|
72
71
|
StructureRelationCategory,
|
|
73
72
|
Term,
|
|
74
73
|
)
|
|
75
|
-
|
|
76
74
|
from kraph.datalayer import DataLayer
|
|
77
75
|
from kraph.kraph import Kraph
|
|
78
76
|
from kraph.links.upload import UploadLink
|
|
@@ -100,11 +98,17 @@ TESTED = tested_against("kraph")
|
|
|
100
98
|
def kraph(
|
|
101
99
|
kraph: Annotated[
|
|
102
100
|
Alias,
|
|
103
|
-
Require(
|
|
101
|
+
Require(
|
|
102
|
+
"live.arkitekt.kraph",
|
|
103
|
+
"Where the knowledge graph relating entities lives",
|
|
104
|
+
version=TESTED,
|
|
105
|
+
),
|
|
104
106
|
],
|
|
105
107
|
datalayer: Annotated[
|
|
106
108
|
Alias | None,
|
|
107
|
-
Require(
|
|
109
|
+
Require(
|
|
110
|
+
"live.arkitekt.s3", "Where the graph's files are stored", optional=True
|
|
111
|
+
),
|
|
108
112
|
],
|
|
109
113
|
tokens: TokenLoader,
|
|
110
114
|
) -> Kraph:
|
|
@@ -125,11 +129,19 @@ def kraph(
|
|
|
125
129
|
FaktsAuthLink(token_loader=tokens),
|
|
126
130
|
UploadLink(datalayer=store),
|
|
127
131
|
SplitLink(
|
|
128
|
-
left=AIOHttpLink(
|
|
129
|
-
|
|
132
|
+
left=AIOHttpLink(
|
|
133
|
+
endpoint_url=kraph.to_http_path("graphql"),
|
|
134
|
+
proxy=kraph.proxy,
|
|
135
|
+
ssl_context=kraph.ssl_context(),
|
|
136
|
+
),
|
|
137
|
+
right=GraphQLWSLink(
|
|
138
|
+
ws_endpoint_url=kraph.to_ws_path("graphql"),
|
|
139
|
+
proxy=kraph.proxy,
|
|
140
|
+
ssl_context=kraph.ssl_context(),
|
|
141
|
+
),
|
|
130
142
|
split=lambda o: o.node.operation != OperationType.SUBSCRIPTION,
|
|
131
143
|
),
|
|
132
|
-
)
|
|
144
|
+
),
|
|
133
145
|
),
|
|
134
146
|
datalayer=store,
|
|
135
147
|
)
|
|
@@ -149,14 +161,16 @@ async def expand_graph(id: str, kraph: Kraph) -> Graph:
|
|
|
149
161
|
return await kraph.aget_graph(id)
|
|
150
162
|
|
|
151
163
|
|
|
152
|
-
@registry.structure(
|
|
164
|
+
@registry.structure(
|
|
165
|
+
"@kraph/entitycategory", widget=_search(SearchEntityCategoriesQuery)
|
|
153
166
|
)
|
|
154
167
|
async def expand_entity_category(id: str, kraph: Kraph) -> EntityCategory:
|
|
155
168
|
"""An entity category, by id."""
|
|
156
169
|
return await kraph.aget_entity_category(id)
|
|
157
170
|
|
|
158
171
|
|
|
159
|
-
@registry.structure(
|
|
172
|
+
@registry.structure(
|
|
173
|
+
"@kraph/relationcategory",
|
|
160
174
|
widget=_search(SearchRelationCategoriesQuery),
|
|
161
175
|
)
|
|
162
176
|
async def expand_relation_category(id: str, kraph: Kraph) -> RelationCategory:
|
|
@@ -164,7 +178,8 @@ async def expand_relation_category(id: str, kraph: Kraph) -> RelationCategory:
|
|
|
164
178
|
return await kraph.aget_relation_category(id)
|
|
165
179
|
|
|
166
180
|
|
|
167
|
-
@registry.structure(
|
|
181
|
+
@registry.structure(
|
|
182
|
+
"@kraph/measurementcategory",
|
|
168
183
|
widget=_search(SearchMeasurementCategoriesQuery),
|
|
169
184
|
)
|
|
170
185
|
async def expand_measurement_category(id: str, kraph: Kraph) -> MeasurementCategory:
|
|
@@ -172,7 +187,8 @@ async def expand_measurement_category(id: str, kraph: Kraph) -> MeasurementCateg
|
|
|
172
187
|
return await kraph.aget_measurement_category(id)
|
|
173
188
|
|
|
174
189
|
|
|
175
|
-
@registry.structure(
|
|
190
|
+
@registry.structure(
|
|
191
|
+
"@kraph/structurerelationcategory",
|
|
176
192
|
widget=_search(SearchStructureRelationCategoriesQuery),
|
|
177
193
|
)
|
|
178
194
|
async def expand_structure_relation_category(
|
|
@@ -182,7 +198,8 @@ async def expand_structure_relation_category(
|
|
|
182
198
|
return await kraph.aget_structure_relation_category(id)
|
|
183
199
|
|
|
184
200
|
|
|
185
|
-
@registry.structure(
|
|
201
|
+
@registry.structure(
|
|
202
|
+
"@kraph/naturaleventcategory",
|
|
186
203
|
widget=_search(SearchNaturalEventCategoriesQuery),
|
|
187
204
|
)
|
|
188
205
|
async def expand_natural_event_category(id: str, kraph: Kraph) -> NaturalEventCategory:
|
|
@@ -190,16 +207,20 @@ async def expand_natural_event_category(id: str, kraph: Kraph) -> NaturalEventCa
|
|
|
190
207
|
return await kraph.aget_natural_event_category(id)
|
|
191
208
|
|
|
192
209
|
|
|
193
|
-
@registry.structure(
|
|
210
|
+
@registry.structure(
|
|
211
|
+
"@kraph/protocoleventcategory",
|
|
194
212
|
widget=_search(SearchProtocolEventCategoriesQuery),
|
|
195
213
|
)
|
|
196
|
-
async def expand_protocol_event_category(
|
|
214
|
+
async def expand_protocol_event_category(
|
|
215
|
+
id: str, kraph: Kraph
|
|
216
|
+
) -> ProtocolEventCategory:
|
|
197
217
|
"""A protocol event category, by id."""
|
|
198
218
|
return await kraph.aget_protocol_event_category(id)
|
|
199
219
|
|
|
200
220
|
|
|
201
221
|
# --- claims ----------------------------------------------------------------------
|
|
202
222
|
|
|
223
|
+
|
|
203
224
|
# `Instance` has no scalar label -- its name lives at `term { key }` -- so it gets no
|
|
204
225
|
# search widget: a two-field `value`/`label` projection cannot reach it.
|
|
205
226
|
@registry.structure("@kraph/entity")
|
|
@@ -236,7 +257,8 @@ async def expand_term(id: str, kraph: Kraph) -> Term:
|
|
|
236
257
|
|
|
237
258
|
|
|
238
259
|
# Identifier kept for wire compatibility; the type behind it is now StructureKind.
|
|
239
|
-
@registry.structure(
|
|
260
|
+
@registry.structure(
|
|
261
|
+
"@kraph/structurecategory", widget=_search(SearchStructureKindsQuery)
|
|
240
262
|
)
|
|
241
263
|
async def expand_structure_kind(id: str, kraph: Kraph) -> StructureKind:
|
|
242
264
|
"""A structure kind, by id -- it travels as `@kraph/structurecategory`."""
|
|
@@ -244,8 +266,7 @@ async def expand_structure_kind(id: str, kraph: Kraph) -> StructureKind:
|
|
|
244
266
|
|
|
245
267
|
|
|
246
268
|
# Identifier kept for wire compatibility; the type behind it is now MetricKind.
|
|
247
|
-
@registry.structure("@kraph/metriccategory", widget=_search(SearchMetricKindsQuery)
|
|
248
|
-
)
|
|
269
|
+
@registry.structure("@kraph/metriccategory", widget=_search(SearchMetricKindsQuery))
|
|
249
270
|
async def expand_metric_kind(id: str, kraph: Kraph) -> MetricKind:
|
|
250
271
|
"""A metric kind, by id -- it travels as `@kraph/metriccategory`."""
|
|
251
272
|
return await kraph.aget_metric_kind(id)
|
|
@@ -266,7 +287,11 @@ def describe_pairs_query(query: GraphPairsQuery) -> dict:
|
|
|
266
287
|
|
|
267
288
|
# The search widgets forward a port's `requires` ($requires), so a picker for a typed port
|
|
268
289
|
# offers only the queries and runs that port accepts.
|
|
269
|
-
@registry.structure(
|
|
290
|
+
@registry.structure(
|
|
291
|
+
"@kraph/pairsquery",
|
|
292
|
+
widget=_search(SearchGraphPairsQueriesQuery),
|
|
293
|
+
describe=describe_pairs_query,
|
|
294
|
+
)
|
|
270
295
|
async def expand_pairs_query(id: str, kraph: Kraph) -> GraphPairsQuery:
|
|
271
296
|
"""A pairs query, by id: an insight over a view that selects pairs from its drawing."""
|
|
272
297
|
return await kraph.aget_graph_pairs_query(id)
|
|
@@ -277,7 +302,11 @@ def describe_pairs_run(run: PairsQueryRun) -> dict:
|
|
|
277
302
|
return dict(run.descriptors or {})
|
|
278
303
|
|
|
279
304
|
|
|
280
|
-
@registry.structure(
|
|
305
|
+
@registry.structure(
|
|
306
|
+
"@kraph/pairsrun",
|
|
307
|
+
widget=_search(SearchPairsQueryRunsQuery),
|
|
308
|
+
describe=describe_pairs_run,
|
|
309
|
+
)
|
|
281
310
|
async def expand_pairs_run(id: str, kraph: Kraph) -> PairsQueryRun:
|
|
282
311
|
"""A run, by id: a pairs query's answer stored with where the drawing stood."""
|
|
283
312
|
return await kraph.aget_pairs_query_run(id)
|
|
@@ -293,7 +322,9 @@ def describe_model(model: Model) -> dict:
|
|
|
293
322
|
return dict(model.descriptors or {})
|
|
294
323
|
|
|
295
324
|
|
|
296
|
-
@registry.structure(
|
|
325
|
+
@registry.structure(
|
|
326
|
+
"@kraph/model", widget=_search(SearchModelsQuery), describe=describe_model
|
|
327
|
+
)
|
|
297
328
|
async def expand_model(id: str, kraph: Kraph) -> Model:
|
|
298
329
|
"""A trained model, by id: its weights and the pairs query run it learned from."""
|
|
299
330
|
return await kraph.aget_model(id)
|
|
@@ -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
|
|
@@ -21,7 +21,6 @@ from typing import Any
|
|
|
21
21
|
|
|
22
22
|
from koil import unkoil, unkoil_gen
|
|
23
23
|
from koil.composition import Composition
|
|
24
|
-
from pydantic import Field
|
|
25
24
|
from rath.origin import origin_context
|
|
26
25
|
from rath.task import TASK_HEADER, TaskLike, current_task, token_of
|
|
27
26
|
from rath.turms.funcs import TOperation
|
|
@@ -31,8 +30,6 @@ from kraph.datalayer import DataLayer
|
|
|
31
30
|
from kraph.rath import KraphRath
|
|
32
31
|
|
|
33
32
|
|
|
34
|
-
|
|
35
|
-
|
|
36
33
|
class Kraph(Composition, KraphApi):
|
|
37
34
|
"""The kraph client.
|
|
38
35
|
|
|
@@ -46,17 +43,24 @@ class Kraph(Composition, KraphApi):
|
|
|
46
43
|
rath: KraphRath
|
|
47
44
|
datalayer: DataLayer
|
|
48
45
|
|
|
49
|
-
|
|
50
46
|
@staticmethod
|
|
51
|
-
def _serialize(
|
|
47
|
+
def _serialize(
|
|
48
|
+
operation: type[TOperation], variables: dict[str, Any]
|
|
49
|
+
) -> dict[str, Any]:
|
|
52
50
|
# exclude_none, not exclude_unset: see the module docstring.
|
|
53
|
-
return operation.Arguments(**variables).model_dump(
|
|
51
|
+
return operation.Arguments(**variables).model_dump(
|
|
52
|
+
by_alias=True, exclude_none=True
|
|
53
|
+
)
|
|
54
54
|
|
|
55
|
-
async def _aprepare(
|
|
55
|
+
async def _aprepare(
|
|
56
|
+
self, operation: type[TOperation], variables: dict[str, Any]
|
|
57
|
+
) -> dict[str, Any]:
|
|
56
58
|
"""Serialize the variables, then run the rath's middlewares over them (uploads, in order)."""
|
|
57
59
|
serialized = self._serialize(operation, variables)
|
|
58
60
|
for middleware in self.rath.middlewares:
|
|
59
|
-
serialized = await middleware.aprocess_variables(
|
|
61
|
+
serialized = await middleware.aprocess_variables(
|
|
62
|
+
serialized, operation, self.rath
|
|
63
|
+
)
|
|
60
64
|
return serialized
|
|
61
65
|
|
|
62
66
|
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)
|
|
@@ -43,20 +43,36 @@ def _end(descriptor: Any) -> tuple[list[str], list[Any]]: # noqa: ANN401
|
|
|
43
43
|
"""The identifiers and the pinned constraints of one end of a category."""
|
|
44
44
|
if descriptor is None:
|
|
45
45
|
return [], []
|
|
46
|
-
return list(getattr(descriptor, "identifiers", None) or []), list(
|
|
46
|
+
return list(getattr(descriptor, "identifiers", None) or []), list(
|
|
47
|
+
getattr(descriptor, "requires", None) or []
|
|
48
|
+
)
|
|
47
49
|
|
|
48
50
|
|
|
49
|
-
def _hold(
|
|
51
|
+
def _hold(
|
|
52
|
+
name: str,
|
|
53
|
+
end: tuple[str, str],
|
|
54
|
+
descriptor: Any, # noqa: ANN401
|
|
55
|
+
check: Check | None,
|
|
56
|
+
) -> None:
|
|
50
57
|
identifiers, requires = _end(descriptor)
|
|
51
58
|
if identifiers and end[0] not in identifiers:
|
|
52
|
-
raise PinRefused(
|
|
59
|
+
raise PinRefused(
|
|
60
|
+
f"The {name} is a {end[0]}, but this word pairs {', '.join(identifiers)} there"
|
|
61
|
+
)
|
|
53
62
|
if not requires:
|
|
54
63
|
return
|
|
55
64
|
if check is None:
|
|
56
|
-
raise PinRefused(
|
|
65
|
+
raise PinRefused(
|
|
66
|
+
f"This word pins {len(requires)} descriptor(s) on its {name}, and only the datum's own service can say whether they hold: pass check="
|
|
67
|
+
)
|
|
57
68
|
if not check(end, requires):
|
|
58
|
-
pinned = ", ".join(
|
|
59
|
-
|
|
69
|
+
pinned = ", ".join(
|
|
70
|
+
f"{c.key} {getattr(c.operator, 'value', c.operator)} {c.value!r}"
|
|
71
|
+
for c in requires
|
|
72
|
+
)
|
|
73
|
+
raise PinRefused(
|
|
74
|
+
f"The {name} {end[0]}:{end[1]} does not satisfy what this word pins there: {pinned}"
|
|
75
|
+
)
|
|
60
76
|
|
|
61
77
|
|
|
62
78
|
def _word(category: Any) -> str: # noqa: ANN401
|
|
@@ -92,7 +108,9 @@ def pair(
|
|
|
92
108
|
_hold("target", target_end, getattr(category, "target_descriptor", None), check)
|
|
93
109
|
|
|
94
110
|
structures = [
|
|
95
|
-
client.assert_structure_exists(
|
|
111
|
+
client.assert_structure_exists(
|
|
112
|
+
identifier=identifier, object=object_id
|
|
113
|
+
).structure
|
|
96
114
|
for identifier, object_id in (source_end, target_end)
|
|
97
115
|
]
|
|
98
116
|
return client.assert_structure_relation_exists(
|
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
from types import TracebackType
|
|
2
|
+
from typing import TypeVar
|
|
3
|
+
|
|
2
4
|
from pydantic import Field
|
|
3
|
-
from kraph.links.upload import UploadLink
|
|
4
|
-
from kraph.middleware.base import OperationMiddleware
|
|
5
5
|
from rath import rath
|
|
6
|
-
|
|
7
6
|
from rath.links.auth import AuthTokenLink
|
|
8
|
-
|
|
9
7
|
from rath.links.compose import TypedComposedLink
|
|
10
8
|
from rath.links.dictinglink import DictingLink
|
|
11
9
|
from rath.links.shrink import ShrinkingLink
|
|
12
10
|
from rath.links.split import SplitLink
|
|
13
11
|
|
|
12
|
+
from kraph.links.upload import UploadLink
|
|
13
|
+
from kraph.middleware.base import OperationMiddleware
|
|
14
|
+
|
|
14
15
|
|
|
15
16
|
class KraphLinkComposition(TypedComposedLink):
|
|
16
17
|
shrinking: ShrinkingLink = Field(default_factory=ShrinkingLink)
|
|
@@ -20,6 +21,9 @@ class KraphLinkComposition(TypedComposedLink):
|
|
|
20
21
|
split: SplitLink
|
|
21
22
|
|
|
22
23
|
|
|
24
|
+
_KraphRath = TypeVar("_KraphRath", bound="KraphRath")
|
|
25
|
+
|
|
26
|
+
|
|
23
27
|
class KraphRath(rath.Rath):
|
|
24
28
|
"""Kraph Rath
|
|
25
29
|
|
|
@@ -30,7 +34,7 @@ class KraphRath(rath.Rath):
|
|
|
30
34
|
|
|
31
35
|
middlewares: list[OperationMiddleware] = Field(default_factory=list)
|
|
32
36
|
|
|
33
|
-
async def __aenter__(self):
|
|
37
|
+
async def __aenter__(self: _KraphRath) -> _KraphRath:
|
|
34
38
|
"""Enter the client and its middlewares.
|
|
35
39
|
|
|
36
40
|
Entering does not make it "the current client", and kraph never looks one up: calls go
|
|
@@ -112,7 +112,7 @@ def as_structure_ref(x: StructureRef) -> tuple[str, str]:
|
|
|
112
112
|
raise TypeError(f"Cannot read a structure reference out of {type(x).__name__}")
|
|
113
113
|
|
|
114
114
|
|
|
115
|
-
def as_term(x:
|
|
115
|
+
def as_term(x: object) -> str:
|
|
116
116
|
"""The word a claim is stated in — a ``Term.key``, never a category id."""
|
|
117
117
|
if isinstance(x, str):
|
|
118
118
|
return x
|
|
@@ -76,7 +76,9 @@ class StructureIdentifier(str):
|
|
|
76
76
|
return cls(identifier_for_cls(target))
|
|
77
77
|
|
|
78
78
|
if isinstance(v, str):
|
|
79
|
-
assert "@" in v,
|
|
79
|
+
assert "@" in v, (
|
|
80
|
+
f"{v!r} is not a valid structure identifier (expected '@ns/name')"
|
|
81
|
+
)
|
|
80
82
|
return cls(v)
|
|
81
83
|
|
|
82
84
|
raise TypeError(
|
|
@@ -106,7 +108,9 @@ class StructureObject(str):
|
|
|
106
108
|
return cls(str(get_attributes_or_error(v, "id")))
|
|
107
109
|
if isinstance(v, (str, int)):
|
|
108
110
|
return cls(str(v))
|
|
109
|
-
raise TypeError(
|
|
111
|
+
raise TypeError(
|
|
112
|
+
"A structure object must be a string, an int, or a model with an id"
|
|
113
|
+
)
|
|
110
114
|
|
|
111
115
|
|
|
112
116
|
class CypherLiteral(str):
|
|
@@ -153,7 +157,9 @@ class BigFile:
|
|
|
153
157
|
handler: GetCoreSchemaHandler,
|
|
154
158
|
) -> CoreSchema:
|
|
155
159
|
"""Validate with :meth:`validate`; the instance travels to the middleware as itself."""
|
|
156
|
-
return core_schema.no_info_after_validator_function(
|
|
160
|
+
return core_schema.no_info_after_validator_function(
|
|
161
|
+
cls.validate, handler(object)
|
|
162
|
+
)
|
|
157
163
|
|
|
158
164
|
@classmethod
|
|
159
165
|
def validate(cls, v: "BigFileLikeCoercible | BigFile") -> "BigFile":
|
|
@@ -163,7 +169,9 @@ class BigFile:
|
|
|
163
169
|
if isinstance(v, (str, os.PathLike)):
|
|
164
170
|
return cls(open(v, "rb"), file_name=os.path.basename(os.fspath(v))) # noqa: SIM115 - read by the upload, closed with it
|
|
165
171
|
if not isinstance(v, io.IOBase):
|
|
166
|
-
raise ValueError(
|
|
172
|
+
raise ValueError(
|
|
173
|
+
f"A big file is a path or an open binary file, not {type(v).__name__}"
|
|
174
|
+
)
|
|
167
175
|
return cls(v)
|
|
168
176
|
|
|
169
177
|
def __repr__(self) -> str:
|
|
@@ -27,6 +27,7 @@ from typing import TYPE_CHECKING, Any
|
|
|
27
27
|
from koil import unkoil
|
|
28
28
|
from pydantic import BaseModel
|
|
29
29
|
from rath.origin import ContextBound
|
|
30
|
+
from rath.scalars import WithId
|
|
30
31
|
from rath.turms.utils import get_attributes_or_error
|
|
31
32
|
|
|
32
33
|
from kraph.client import client_of
|
|
@@ -34,6 +35,7 @@ from kraph.client import client_of
|
|
|
34
35
|
if TYPE_CHECKING:
|
|
35
36
|
from arkitekt_spec.declare.structures.registry import StructureRegistry
|
|
36
37
|
|
|
38
|
+
from kraph.api.schema import GraphProjection
|
|
37
39
|
from kraph.kraph import Kraph
|
|
38
40
|
|
|
39
41
|
|
|
@@ -56,9 +58,17 @@ class AssertedTrait(BaseModel):
|
|
|
56
58
|
return get_attributes_or_error(self, "assertion").seq
|
|
57
59
|
|
|
58
60
|
@property
|
|
59
|
-
def claim(self) ->
|
|
61
|
+
def claim(self) -> object:
|
|
60
62
|
"""The thing this write recorded, whichever field the payload carries it in."""
|
|
61
|
-
for field in (
|
|
63
|
+
for field in (
|
|
64
|
+
"instance",
|
|
65
|
+
"instances",
|
|
66
|
+
"link",
|
|
67
|
+
"links",
|
|
68
|
+
"structure",
|
|
69
|
+
"metric",
|
|
70
|
+
"comment",
|
|
71
|
+
):
|
|
62
72
|
value = getattr(self, field, None)
|
|
63
73
|
if value is not None:
|
|
64
74
|
return value
|
|
@@ -87,9 +97,11 @@ class HasDrawings(BaseModel):
|
|
|
87
97
|
"""
|
|
88
98
|
return bool(get_attributes_or_error(self, "drawings"))
|
|
89
99
|
|
|
90
|
-
def drawn_in(self, graph:
|
|
100
|
+
def drawn_in(self, graph: str | WithId) -> object | None:
|
|
91
101
|
"""This view's account of the claim, or ``None`` if this view does not draw it."""
|
|
92
|
-
wanted =
|
|
102
|
+
wanted = (
|
|
103
|
+
graph if isinstance(graph, str) else get_attributes_or_error(graph, "id")
|
|
104
|
+
)
|
|
93
105
|
for drawing in get_attributes_or_error(self, "drawings"):
|
|
94
106
|
if str(drawing.graph.id) == str(wanted):
|
|
95
107
|
return drawing
|
|
@@ -179,7 +191,7 @@ class StructureTrait(BaseModel):
|
|
|
179
191
|
"""The ``(identifier, object)`` pair that addresses this datum."""
|
|
180
192
|
return get_attributes_or_error(self, "identifier", "object")
|
|
181
193
|
|
|
182
|
-
def resolve(self, registry: "StructureRegistry") ->
|
|
194
|
+
def resolve(self, registry: "StructureRegistry") -> object:
|
|
183
195
|
"""Expand this structure back into the concrete Python object it points at.
|
|
184
196
|
|
|
185
197
|
Uses ``registry``, a structure registry bound to its clients (the one a running task
|
|
@@ -265,7 +277,7 @@ class GraphTrait(ContextBound):
|
|
|
265
277
|
"""
|
|
266
278
|
|
|
267
279
|
@property
|
|
268
|
-
def projection_state(self) ->
|
|
280
|
+
def projection_state(self) -> "ProjectionTrait":
|
|
269
281
|
return get_attributes_or_error(self, "projection")
|
|
270
282
|
|
|
271
283
|
def wait_until_projected(
|
|
@@ -275,7 +287,7 @@ class GraphTrait(ContextBound):
|
|
|
275
287
|
timeout: float = 30.0,
|
|
276
288
|
poll: float = 0.5,
|
|
277
289
|
kraph: "Kraph | None" = None,
|
|
278
|
-
) ->
|
|
290
|
+
) -> "GraphProjection":
|
|
279
291
|
"""Block until this view has drawn everything up to ``seq``.
|
|
280
292
|
|
|
281
293
|
Never implicit: a backfill or a category edit redraws in-request and is unbounded in the
|
|
@@ -318,7 +330,9 @@ def structure_identifier(end: Any) -> str: # noqa: ANN401
|
|
|
318
330
|
stamped = getattr(end, "__identifier__", None)
|
|
319
331
|
if isinstance(stamped, str):
|
|
320
332
|
return stamped
|
|
321
|
-
raise TypeError(
|
|
333
|
+
raise TypeError(
|
|
334
|
+
f"A pair's end is a structure identifier ('@mikro/arraylens') or a class stamped with one, not {end!r}"
|
|
335
|
+
)
|
|
322
336
|
|
|
323
337
|
|
|
324
338
|
def _typed_by_ends(cls: type, ends: Any, name: str) -> Any: # noqa: ANN401
|
|
@@ -338,8 +352,12 @@ def _typed_by_ends(cls: type, ends: Any, name: str) -> Any: # noqa: ANN401
|
|
|
338
352
|
source, target = (structure_identifier(end) for end in ends)
|
|
339
353
|
return Annotated[
|
|
340
354
|
cls,
|
|
341
|
-
Requires(
|
|
342
|
-
|
|
355
|
+
Requires(
|
|
356
|
+
key=SOURCE_IDENTIFIER, operator=DescriptorOperator.EQUALS, value=source
|
|
357
|
+
),
|
|
358
|
+
Requires(
|
|
359
|
+
key=TARGET_IDENTIFIER, operator=DescriptorOperator.EQUALS, value=target
|
|
360
|
+
),
|
|
343
361
|
]
|
|
344
362
|
|
|
345
363
|
|
|
@@ -361,7 +379,13 @@ def _expanded(registry: "StructureRegistry", pairs: list[Any]) -> list[tuple[Any
|
|
|
361
379
|
def expand(identifier: str, object_id: str) -> Any: # noqa: ANN401
|
|
362
380
|
return unkoil(registry.get_fullfilled_structure(identifier).expand, object_id)
|
|
363
381
|
|
|
364
|
-
return [
|
|
382
|
+
return [
|
|
383
|
+
(
|
|
384
|
+
expand(pair.source_identifier, pair.source_object),
|
|
385
|
+
expand(pair.target_identifier, pair.target_object),
|
|
386
|
+
)
|
|
387
|
+
for pair in pairs
|
|
388
|
+
]
|
|
365
389
|
|
|
366
390
|
|
|
367
391
|
class GraphPairsQueryTrait(ContextBound):
|
|
@@ -380,11 +404,22 @@ class GraphPairsQueryTrait(ContextBound):
|
|
|
380
404
|
"""Every pair the query answers now, from the view's drawing. Not a record: run it for one."""
|
|
381
405
|
client = client_of(self, kraph)
|
|
382
406
|
query_id = get_attributes_or_error(self, "id")
|
|
383
|
-
return _read_pairs(
|
|
407
|
+
return _read_pairs(
|
|
408
|
+
lambda pagination: client.render_graph_pairs(
|
|
409
|
+
id=query_id, pagination=pagination
|
|
410
|
+
),
|
|
411
|
+
page,
|
|
412
|
+
)
|
|
384
413
|
|
|
385
|
-
def run(
|
|
414
|
+
def run(
|
|
415
|
+
self, name: str, *, description: str | None = None, kraph: "Kraph | None" = None
|
|
416
|
+
) -> Any: # noqa: ANN401
|
|
386
417
|
"""Run the query: its answer, stored with where the drawing stood. What a model cites."""
|
|
387
|
-
return client_of(self, kraph).run_pairs_query(
|
|
418
|
+
return client_of(self, kraph).run_pairs_query(
|
|
419
|
+
query=get_attributes_or_error(self, "id"),
|
|
420
|
+
name=name,
|
|
421
|
+
description=description,
|
|
422
|
+
)
|
|
388
423
|
|
|
389
424
|
|
|
390
425
|
class PairsQueryRunTrait(ContextBound):
|
|
@@ -399,13 +434,22 @@ class PairsQueryRunTrait(ContextBound):
|
|
|
399
434
|
"""``PairsQueryRun["@mikro/arraylens", "@mikro/arraylens"]``: runs of image pairs only."""
|
|
400
435
|
return _typed_by_ends(cls, ends, "PairsQueryRun")
|
|
401
436
|
|
|
402
|
-
def read_entries(
|
|
437
|
+
def read_entries(
|
|
438
|
+
self, *, kraph: "Kraph | None" = None, page: int = 1000
|
|
439
|
+
) -> list[Any]:
|
|
403
440
|
"""Every stored pair, in the run's order, as ``(identifier, object)`` addresses."""
|
|
404
441
|
client = client_of(self, kraph)
|
|
405
442
|
run_id = get_attributes_or_error(self, "id")
|
|
406
|
-
return _read_pairs(
|
|
443
|
+
return _read_pairs(
|
|
444
|
+
lambda pagination: (
|
|
445
|
+
client.get_run_entries(id=run_id, pagination=pagination).page
|
|
446
|
+
),
|
|
447
|
+
page,
|
|
448
|
+
)
|
|
407
449
|
|
|
408
|
-
def pairs(
|
|
450
|
+
def pairs(
|
|
451
|
+
self, registry: "StructureRegistry", *, kraph: "Kraph | None" = None
|
|
452
|
+
) -> list[tuple[Any, Any]]:
|
|
409
453
|
"""Every pair as the objects themselves: ``(source, target)``, each expanded by its own service.
|
|
410
454
|
|
|
411
455
|
``registry`` is a structure registry bound to its clients (the one a running task
|
|
@@ -418,17 +462,29 @@ class PairsQueryRunTrait(ContextBound):
|
|
|
418
462
|
class BigFileStoreTrait(ContextBound):
|
|
419
463
|
"""A big file in kraph's datalayer: read back through an access grant, never by its path."""
|
|
420
464
|
|
|
421
|
-
def download(
|
|
465
|
+
def download(
|
|
466
|
+
self, file_name: str | None = None, *, kraph: "Kraph | None" = None
|
|
467
|
+
) -> str:
|
|
422
468
|
"""Stream the file to ``file_name`` (its uploaded name by default). Returns the path written."""
|
|
423
469
|
from kraph.io.download import download_bigfile, file_name_of
|
|
424
470
|
|
|
425
|
-
return download_bigfile(
|
|
471
|
+
return download_bigfile(
|
|
472
|
+
str(get_attributes_or_error(self, "id")),
|
|
473
|
+
file_name_of(self, file_name),
|
|
474
|
+
client_of(self, kraph),
|
|
475
|
+
)
|
|
426
476
|
|
|
427
|
-
async def adownload(
|
|
477
|
+
async def adownload(
|
|
478
|
+
self, file_name: str | None = None, *, kraph: "Kraph | None" = None
|
|
479
|
+
) -> str:
|
|
428
480
|
"""Stream the file to ``file_name`` (its uploaded name by default). Returns the path written."""
|
|
429
481
|
from kraph.io.download import adownload_bigfile, file_name_of
|
|
430
482
|
|
|
431
|
-
return await adownload_bigfile(
|
|
483
|
+
return await adownload_bigfile(
|
|
484
|
+
str(get_attributes_or_error(self, "id")),
|
|
485
|
+
file_name_of(self, file_name),
|
|
486
|
+
client_of(self, kraph),
|
|
487
|
+
)
|
|
432
488
|
|
|
433
489
|
|
|
434
490
|
class ModelTrait(ContextBound):
|
|
@@ -438,16 +494,28 @@ class ModelTrait(ContextBound):
|
|
|
438
494
|
sends the file and passes the finished store on, as every service's files are uploaded.
|
|
439
495
|
"""
|
|
440
496
|
|
|
441
|
-
def download(
|
|
497
|
+
def download(
|
|
498
|
+
self, file_name: str | None = None, *, kraph: "Kraph | None" = None
|
|
499
|
+
) -> str:
|
|
442
500
|
"""Stream the weights to ``file_name`` (their uploaded name by default). Returns the path written."""
|
|
443
501
|
from kraph.io.download import download_bigfile, file_name_of
|
|
444
502
|
|
|
445
503
|
store = get_attributes_or_error(self, "store")
|
|
446
|
-
return download_bigfile(
|
|
504
|
+
return download_bigfile(
|
|
505
|
+
str(get_attributes_or_error(store, "id")),
|
|
506
|
+
file_name_of(store, file_name),
|
|
507
|
+
client_of(self, kraph),
|
|
508
|
+
)
|
|
447
509
|
|
|
448
|
-
async def adownload(
|
|
510
|
+
async def adownload(
|
|
511
|
+
self, file_name: str | None = None, *, kraph: "Kraph | None" = None
|
|
512
|
+
) -> str:
|
|
449
513
|
"""Stream the weights to ``file_name`` (their uploaded name by default). Returns the path written."""
|
|
450
514
|
from kraph.io.download import adownload_bigfile, file_name_of
|
|
451
515
|
|
|
452
516
|
store = get_attributes_or_error(self, "store")
|
|
453
|
-
return await adownload_bigfile(
|
|
517
|
+
return await adownload_bigfile(
|
|
518
|
+
str(get_attributes_or_error(store, "id")),
|
|
519
|
+
file_name_of(store, file_name),
|
|
520
|
+
client_of(self, kraph),
|
|
521
|
+
)
|
|
@@ -33,52 +33,10 @@ dev-dependencies = [
|
|
|
33
33
|
"aiohttp>=3.8.3,<4",
|
|
34
34
|
"black>=23.1.0,<24",
|
|
35
35
|
"pytest-aiohttp>=1.0.4,<2",
|
|
36
|
-
"ruff>=0.0.254",
|
|
37
36
|
"turms>=3.0",
|
|
38
37
|
"dokker>=2.8",
|
|
39
|
-
"basedpyright>=1.21",
|
|
40
38
|
]
|
|
41
39
|
|
|
42
|
-
[tool.basedpyright]
|
|
43
|
-
include = ["kraph"]
|
|
44
|
-
exclude = ["**/__pycache__", "tests"]
|
|
45
|
-
typeCheckingMode = "standard"
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
[tool.ruff]
|
|
49
|
-
extend-select = ["ANN", "D1", "UP"]
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
# Exclude a variety of commonly ignored directories.
|
|
53
|
-
exclude = [
|
|
54
|
-
".bzr",
|
|
55
|
-
".direnv",
|
|
56
|
-
".eggs",
|
|
57
|
-
".git",
|
|
58
|
-
".hg",
|
|
59
|
-
".mypy_cache",
|
|
60
|
-
".nox",
|
|
61
|
-
".pants.d",
|
|
62
|
-
".pytype",
|
|
63
|
-
".ruff_cache",
|
|
64
|
-
".svn",
|
|
65
|
-
".tox",
|
|
66
|
-
".venv",
|
|
67
|
-
"__pypackages__",
|
|
68
|
-
"_build",
|
|
69
|
-
"buck-out",
|
|
70
|
-
"build",
|
|
71
|
-
"dist",
|
|
72
|
-
"node_modules",
|
|
73
|
-
"venv",
|
|
74
|
-
]
|
|
75
|
-
|
|
76
|
-
# Same as Black.
|
|
77
|
-
line-length = 100
|
|
78
|
-
extend-ignore = ["UP037", "UP038", "UP042"]
|
|
79
|
-
|
|
80
|
-
[tool.ruff.lint.per-file-ignores]
|
|
81
|
-
"kraph/api/schema.py" = ["UP035"]
|
|
82
40
|
# `_tested.json` is written by the integration tests (the server version they ran against)
|
|
83
41
|
# and is not in git: named as an artifact, on both, it is shipped all the same.
|
|
84
42
|
[tool.hatch.build.targets.sdist]
|
|
@@ -156,3 +114,9 @@ exclude_commit_patterns = [
|
|
|
156
114
|
'^Merge ',
|
|
157
115
|
]
|
|
158
116
|
|
|
117
|
+
|
|
118
|
+
[dependency-groups]
|
|
119
|
+
dev = [
|
|
120
|
+
"ruff==0.17.6",
|
|
121
|
+
"basedpyright==1.40.2",
|
|
122
|
+
]
|
kraph-7.2.0/kraph/_tested.json
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version": "7.5.0"}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|