nex-datahub 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.
Files changed (55) hide show
  1. nex_datahub-0.2.0/PKG-INFO +38 -0
  2. nex_datahub-0.2.0/README.md +18 -0
  3. nex_datahub-0.2.0/pyproject.toml +50 -0
  4. nex_datahub-0.2.0/setup.cfg +4 -0
  5. nex_datahub-0.2.0/src/nex_datahub/__init__.py +135 -0
  6. nex_datahub-0.2.0/src/nex_datahub/client.py +216 -0
  7. nex_datahub-0.2.0/src/nex_datahub/client.pyi +1789 -0
  8. nex_datahub-0.2.0/src/nex_datahub/collaboration.py +318 -0
  9. nex_datahub-0.2.0/src/nex_datahub/contracts.py +355 -0
  10. nex_datahub-0.2.0/src/nex_datahub/directories.py +393 -0
  11. nex_datahub-0.2.0/src/nex_datahub/errors.py +104 -0
  12. nex_datahub-0.2.0/src/nex_datahub/files.py +761 -0
  13. nex_datahub-0.2.0/src/nex_datahub/filesystem.py +278 -0
  14. nex_datahub-0.2.0/src/nex_datahub/jsonutil.py +146 -0
  15. nex_datahub-0.2.0/src/nex_datahub/models.py +501 -0
  16. nex_datahub-0.2.0/src/nex_datahub/py.typed +0 -0
  17. nex_datahub-0.2.0/src/nex_datahub/resources.py +597 -0
  18. nex_datahub-0.2.0/src/nex_datahub/results.py +377 -0
  19. nex_datahub-0.2.0/src/nex_datahub/routing.py +339 -0
  20. nex_datahub-0.2.0/src/nex_datahub/schemas/resources.schema.json +5210 -0
  21. nex_datahub-0.2.0/src/nex_datahub/schemas/task-body.v1.schema.json +924 -0
  22. nex_datahub-0.2.0/src/nex_datahub/schemas/trace-body.v1.schema.json +1364 -0
  23. nex_datahub-0.2.0/src/nex_datahub/schemas/trace-body.v2.schema.json +1380 -0
  24. nex_datahub-0.2.0/src/nex_datahub/schemas/tree.v1.schema.json +111 -0
  25. nex_datahub-0.2.0/src/nex_datahub/storage_models.py +78 -0
  26. nex_datahub-0.2.0/src/nex_datahub/task_types.py +22 -0
  27. nex_datahub-0.2.0/src/nex_datahub/transfer_utils.py +101 -0
  28. nex_datahub-0.2.0/src/nex_datahub/transport.py +276 -0
  29. nex_datahub-0.2.0/src/nex_datahub/tree.py +75 -0
  30. nex_datahub-0.2.0/src/nex_datahub.egg-info/PKG-INFO +38 -0
  31. nex_datahub-0.2.0/src/nex_datahub.egg-info/SOURCES.txt +53 -0
  32. nex_datahub-0.2.0/src/nex_datahub.egg-info/dependency_links.txt +1 -0
  33. nex_datahub-0.2.0/src/nex_datahub.egg-info/requires.txt +13 -0
  34. nex_datahub-0.2.0/src/nex_datahub.egg-info/top_level.txt +1 -0
  35. nex_datahub-0.2.0/tests/test_batch_budget.py +122 -0
  36. nex_datahub-0.2.0/tests/test_capacity.py +60 -0
  37. nex_datahub-0.2.0/tests/test_collaboration.py +287 -0
  38. nex_datahub-0.2.0/tests/test_collaboration_live.py +122 -0
  39. nex_datahub-0.2.0/tests/test_collection_filters.py +105 -0
  40. nex_datahub-0.2.0/tests/test_directories.py +268 -0
  41. nex_datahub-0.2.0/tests/test_directory_restore.py +336 -0
  42. nex_datahub-0.2.0/tests/test_endpoint_routing.py +573 -0
  43. nex_datahub-0.2.0/tests/test_external_keys.py +116 -0
  44. nex_datahub-0.2.0/tests/test_identity.py +72 -0
  45. nex_datahub-0.2.0/tests/test_instance_identity.py +46 -0
  46. nex_datahub-0.2.0/tests/test_live.py +450 -0
  47. nex_datahub-0.2.0/tests/test_models.py +153 -0
  48. nex_datahub-0.2.0/tests/test_partial_batch_receipts.py +151 -0
  49. nex_datahub-0.2.0/tests/test_results.py +180 -0
  50. nex_datahub-0.2.0/tests/test_rfc14_live.py +169 -0
  51. nex_datahub-0.2.0/tests/test_schema_references.py +39 -0
  52. nex_datahub-0.2.0/tests/test_snapshot_memory.py +128 -0
  53. nex_datahub-0.2.0/tests/test_task_types.py +99 -0
  54. nex_datahub-0.2.0/tests/test_transport.py +399 -0
  55. nex_datahub-0.2.0/tests/test_write_receipts.py +175 -0
@@ -0,0 +1,38 @@
1
+ Metadata-Version: 2.4
2
+ Name: nex_datahub
3
+ Version: 0.2.0
4
+ Summary: Python SDK for NexDataHub
5
+ License: Proprietary
6
+ Requires-Python: >=3.11
7
+ Description-Content-Type: text/markdown
8
+ Requires-Dist: pydantic>=2.9
9
+ Requires-Dist: httpx>=0.27
10
+ Requires-Dist: rfc8785>=0.1.4
11
+ Requires-Dist: jsonschema>=4.23
12
+ Provides-Extra: dev
13
+ Requires-Dist: pytest>=8; extra == "dev"
14
+ Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
15
+ Requires-Dist: ruff>=0.6; extra == "dev"
16
+ Requires-Dist: pyyaml>=6; extra == "dev"
17
+ Requires-Dist: sqlalchemy>=2; extra == "dev"
18
+ Requires-Dist: psycopg[binary]>=3.2; extra == "dev"
19
+ Requires-Dist: pyright>=1.1.414; extra == "dev"
20
+
21
+ # NexDataHub Python SDK
22
+
23
+ 同步 Client 与异步 AsyncClient,独立安装支持 Python 3.11+。从 NexLab 根目录:
24
+
25
+ ```bash
26
+ python -m pip install ./components/datahub/sdk/python
27
+ ```
28
+
29
+ ```python
30
+ from getpass import getpass
31
+ from nex_datahub import Client
32
+
33
+ with Client(base_url="http://127.0.0.1:18080", token=getpass("Token: ")) as hub:
34
+ for task in hub.tasks.iter(limit=10):
35
+ print(task.id, task.name)
36
+ ```
37
+
38
+ [Python 指南](../../../../docs/datahub/guide.md)介绍完整使用流程;[接口参考](../../../../docs/datahub/reference/api.md)说明读取、分页、批量和对象方法;[资源结构](../../../../docs/datahub/reference/resources.md)定义字段与修改边界。完整静态签名位于 [client.pyi](src/nex_datahub/client.pyi),HTTP 契约位于 [OpenAPI](../../contracts/openapi.json)。
@@ -0,0 +1,18 @@
1
+ # NexDataHub Python SDK
2
+
3
+ 同步 Client 与异步 AsyncClient,独立安装支持 Python 3.11+。从 NexLab 根目录:
4
+
5
+ ```bash
6
+ python -m pip install ./components/datahub/sdk/python
7
+ ```
8
+
9
+ ```python
10
+ from getpass import getpass
11
+ from nex_datahub import Client
12
+
13
+ with Client(base_url="http://127.0.0.1:18080", token=getpass("Token: ")) as hub:
14
+ for task in hub.tasks.iter(limit=10):
15
+ print(task.id, task.name)
16
+ ```
17
+
18
+ [Python 指南](../../../../docs/datahub/guide.md)介绍完整使用流程;[接口参考](../../../../docs/datahub/reference/api.md)说明读取、分页、批量和对象方法;[资源结构](../../../../docs/datahub/reference/resources.md)定义字段与修改边界。完整静态签名位于 [client.pyi](src/nex_datahub/client.pyi),HTTP 契约位于 [OpenAPI](../../contracts/openapi.json)。
@@ -0,0 +1,50 @@
1
+ [build-system]
2
+ requires = ["setuptools>=69"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "nex_datahub"
7
+ version = "0.2.0"
8
+ description = "Python SDK for NexDataHub"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = { text = "Proprietary" }
12
+ dependencies = [
13
+ "pydantic>=2.9",
14
+ "httpx>=0.27",
15
+ "rfc8785>=0.1.4",
16
+ "jsonschema>=4.23",
17
+ ]
18
+
19
+ [project.optional-dependencies]
20
+ dev = [
21
+ "pytest>=8",
22
+ "pytest-asyncio>=0.24",
23
+ "ruff>=0.6",
24
+ "pyyaml>=6",
25
+ "sqlalchemy>=2",
26
+ "psycopg[binary]>=3.2",
27
+ "pyright>=1.1.414",
28
+ ]
29
+
30
+ [tool.setuptools]
31
+ package-dir = { "" = "src" }
32
+
33
+ [tool.setuptools.packages.find]
34
+ where = ["src"]
35
+
36
+ [tool.pytest.ini_options]
37
+ asyncio_mode = "auto"
38
+ testpaths = ["tests"]
39
+
40
+ [tool.ruff]
41
+ line-length = 120
42
+
43
+ [tool.ruff.lint]
44
+ select = ["E", "F", "I"]
45
+
46
+ [tool.ruff.lint.isort]
47
+ known-first-party = ["nex_datahub"]
48
+
49
+ [tool.setuptools.package-data]
50
+ nex_datahub = ["schemas/*.json", "py.typed", "*.pyi"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,135 @@
1
+ """NexDataHub RFC-0001 Python API."""
2
+
3
+ from .client import AsyncClient, Client
4
+ from .collaboration import Comment, Issue, Notification, NotificationSettings, TextReference, UserProfile, UserRef
5
+ from .contracts import TaskBody, TraceBody
6
+ from .directories import DirectoryImport
7
+ from .errors import (
8
+ AuthenticationError,
9
+ ChecksumError,
10
+ ConflictError,
11
+ DataHubError,
12
+ DestinationExistsError,
13
+ NotFoundError,
14
+ PermissionDeniedError,
15
+ ReferencedError,
16
+ SourceChangedError,
17
+ SymlinkError,
18
+ TransportError,
19
+ TypeRestoreError,
20
+ UnsupportedFilesystemError,
21
+ ValidationError,
22
+ )
23
+ from .models import (
24
+ Asset,
25
+ AssetCreate,
26
+ BlobRef,
27
+ BodyRef,
28
+ DirectoryRef,
29
+ DynamicModel,
30
+ Environment,
31
+ EnvironmentCreate,
32
+ FileRef,
33
+ Page,
34
+ Ref,
35
+ Schema,
36
+ SchemaCreate,
37
+ Task,
38
+ TaskCreate,
39
+ TaskSet,
40
+ TaskSetCreate,
41
+ Trace,
42
+ TraceCreate,
43
+ )
44
+ from .storage_models import Directory, DirectoryEntry, File
45
+
46
+ __all__ = [
47
+ "Client",
48
+ "Comment",
49
+ "Issue",
50
+ "Notification",
51
+ "NotificationSettings",
52
+ "TextReference",
53
+ "UserProfile",
54
+ "UserRef",
55
+ "AsyncClient",
56
+ "Schema",
57
+ "Asset",
58
+ "Task",
59
+ "TaskSet",
60
+ "Trace",
61
+ "Environment",
62
+ "EnvironmentCreate",
63
+ "BlobRef",
64
+ "FileRef",
65
+ "DirectoryRef",
66
+ "File",
67
+ "Directory",
68
+ "DirectoryEntry",
69
+ "DirectoryImport",
70
+ "SourceChangedError",
71
+ "UnsupportedFilesystemError",
72
+ "SymlinkError",
73
+ "DestinationExistsError",
74
+ "ChecksumError",
75
+ "Ref",
76
+ "BodyRef",
77
+ "DynamicModel",
78
+ "Page",
79
+ "TaskBody",
80
+ "TraceBody",
81
+ "SchemaCreate",
82
+ "AssetCreate",
83
+ "TaskCreate",
84
+ "TaskSetCreate",
85
+ "TraceCreate",
86
+ "DataHubError",
87
+ "AuthenticationError",
88
+ "ConflictError",
89
+ "NotFoundError",
90
+ "PermissionDeniedError",
91
+ "ReferencedError",
92
+ "TransportError",
93
+ "TypeRestoreError",
94
+ "ValidationError",
95
+ ]
96
+
97
+ from .results import (
98
+ AgentConfiguration,
99
+ AggregationSpec,
100
+ DirectoryOutput,
101
+ Evaluation,
102
+ EvaluationCreate,
103
+ EvaluationItem,
104
+ EvaluationItemPage,
105
+ ExecutionError,
106
+ ExecutorConfiguration,
107
+ FileOutput,
108
+ GenerationResult,
109
+ GitPatchOutput,
110
+ Grade,
111
+ GradeCreate,
112
+ GraderConfiguration,
113
+ Trial,
114
+ TrialCreate,
115
+ )
116
+
117
+ __all__ += [
118
+ "AgentConfiguration",
119
+ "AggregationSpec",
120
+ "ExecutorConfiguration",
121
+ "GraderConfiguration",
122
+ "DirectoryOutput",
123
+ "FileOutput",
124
+ "GitPatchOutput",
125
+ "ExecutionError",
126
+ "GenerationResult",
127
+ "Grade",
128
+ "GradeCreate",
129
+ "Trial",
130
+ "TrialCreate",
131
+ "Evaluation",
132
+ "EvaluationCreate",
133
+ "EvaluationItem",
134
+ "EvaluationItemPage",
135
+ ]
@@ -0,0 +1,216 @@
1
+ """Synchronous and asynchronous DataHub clients with matching business semantics."""
2
+
3
+ import asyncio
4
+ from urllib.parse import quote
5
+
6
+ import httpx
7
+
8
+ from . import jsonutil
9
+ from .collaboration import CollaborationResources, Comment, Issue, Me, UserProfiles
10
+ from .directories import Directories
11
+ from .errors import TransportError, ValidationError
12
+ from .files import Files
13
+ from .models import Snapshot
14
+ from .resources import Assets, Collection, Environments, Resources, Schemas, Tasks, TaskSets, Traces
15
+ from .routing import EndpointRouting
16
+ from .transport import AsyncDriver, Request, SyncDriver, key
17
+
18
+
19
+ class AdminResources:
20
+ def __init__(self, client, resource):
21
+ self.client, self.resource = client, resource
22
+ self.path = "/" + resource
23
+
24
+ def create(self, *, idempotency_key=None, **kwargs):
25
+ if self.resource == "tokens" and idempotency_key is not None:
26
+ raise ValidationError("Token issuance does not accept an idempotency key")
27
+ return self.client._run(self._create(kwargs, idempotency_key))
28
+
29
+ def _create(self, fields, logical_key):
30
+ fields = dict(fields)
31
+ if fields.get("expires_at") is not None:
32
+ fields["expires_at"] = jsonutil.time_string(fields["expires_at"])
33
+ token = self.resource == "tokens"
34
+ value = yield Request("POST", self.path, fields, None if token else key(logical_key), retry=not token)
35
+ obj = Snapshot(value, self.client)
36
+ if token:
37
+ obj._view["token"] = Snapshot(value["token"], self.client)
38
+ return obj
39
+
40
+ def list(self, *, page_size=100, cursor=None, **kwargs):
41
+ return self.client._run(self._list(page_size, cursor, kwargs))
42
+
43
+ def _list(self, page_size, cursor, kwargs):
44
+ from .models import Page
45
+
46
+ body = dict(kwargs, page_size=page_size)
47
+ if cursor is not None:
48
+ body["cursor"] = cursor
49
+ result = yield Request("POST", self.path + ":query", body)
50
+ return Page([Snapshot(v, self.client) for v in result["items"]], result["next_cursor"])
51
+
52
+
53
+ class Users(AdminResources):
54
+ def get(self, id):
55
+ return self.client._run(self._get(id))
56
+
57
+ def _get(self, id):
58
+ value = yield Request("GET", self.path + "/" + self.client._id(id))
59
+ return Snapshot(value, self.client)
60
+
61
+ def update(self, id, *, idempotency_key=None, **kwargs):
62
+ return self.client._run(self._update(id, kwargs, key(idempotency_key)))
63
+
64
+ def _update(self, id, fields, logical_key):
65
+ value = yield Request("PATCH", self.path + "/" + self.client._id(id), fields, logical_key)
66
+ return Snapshot(value, self.client)
67
+
68
+
69
+ class Tokens(AdminResources):
70
+ def delete(self, id, *, idempotency_key=None):
71
+ return self.client._run(self._delete(id, key(idempotency_key)))
72
+
73
+ def _delete(self, id, logical_key):
74
+ yield Request("DELETE", self.path + "/" + self.client._id(id), key=logical_key)
75
+ return None
76
+
77
+
78
+ class BaseClient:
79
+ def _setup(self, base_url, token, max_retries, upload_timeout, endpoint):
80
+ if not isinstance(token, str) or not token:
81
+ raise ValidationError("A nonempty token is required")
82
+ if isinstance(max_retries, bool) or not isinstance(max_retries, int) or max_retries < 0:
83
+ raise ValidationError("max_retries must be a nonnegative integer")
84
+ self._base = base_url.rstrip("/")
85
+ if not self._base.endswith("/api/v1"):
86
+ self._base += "/api/v1"
87
+ self._token, self._retries = token, max_retries
88
+ self._upload_timeout, self._closed = upload_timeout, False
89
+ self._file_routing = EndpointRouting(endpoint)
90
+ self._definitions = {}
91
+ self._leases = set()
92
+ self._lease_tasks = set()
93
+ self.schemas = Schemas(self, "schemas")
94
+ self.assets = Assets(self, "assets")
95
+ self.tasks = Tasks(self, "tasks")
96
+ self.tasksets = TaskSets(self, "tasksets")
97
+ self.traces = Traces(self, "traces")
98
+ self.environments = Environments(self, "environments")
99
+ self.trials = Resources(self, "trials")
100
+ self.grades = Resources(self, "grades")
101
+ self.evaluations = Resources(self, "evaluations")
102
+ self.issues = CollaborationResources(self, "issues", Issue)
103
+ self.comments = CollaborationResources(self, "comments", Comment)
104
+ self.me = Me(self)
105
+ self.user_profiles = UserProfiles(self)
106
+ self.files = Files(self)
107
+ self.dirs = Directories(self)
108
+ self.users, self.tokens = Users(self, "users"), Tokens(self, "tokens")
109
+
110
+ def _check_open(self):
111
+ if self._closed:
112
+ raise TransportError("DataHub client is closed", code="client_closed")
113
+
114
+ @staticmethod
115
+ def _id(value):
116
+ if not isinstance(value, str) or not value:
117
+ raise ValidationError("Expected a nonempty resource ID string")
118
+ return quote(value, safe="")
119
+
120
+ def _associations(self, resource, id):
121
+ return Collection(self, "/" + resource + "/" + id + "/assets", "assets")
122
+
123
+ def _comments(self, parent, id, collection="comments"):
124
+ return Collection(self, f"/{parent}/{self._id(id)}/{collection}", "comments")
125
+
126
+ def _members(self, id, collection):
127
+ return Collection(self, "/tasksets/" + id + "/" + collection, collection)
128
+
129
+
130
+ class Client(SyncDriver, BaseClient):
131
+ def __init__(
132
+ self,
133
+ *,
134
+ base_url,
135
+ token,
136
+ timeout=30,
137
+ max_retries=3,
138
+ file_concurrency=8,
139
+ upload_timeout=86400,
140
+ transport=None,
141
+ cloud_transport=None,
142
+ endpoint="auto",
143
+ ):
144
+ self._setup(base_url, token, max_retries, upload_timeout, endpoint)
145
+ if isinstance(file_concurrency, bool) or not isinstance(file_concurrency, int) or file_concurrency < 1:
146
+ raise ValidationError("file_concurrency must be positive")
147
+ self._file_concurrency = file_concurrency
148
+ self._http = httpx.Client(timeout=timeout, transport=transport, follow_redirects=False)
149
+ self._cloud = httpx.Client(
150
+ timeout=upload_timeout,
151
+ transport=cloud_transport,
152
+ limits=httpx.Limits(max_connections=file_concurrency),
153
+ follow_redirects=False,
154
+ )
155
+
156
+ def close(self):
157
+ if not self._closed:
158
+ for lease in list(self._leases):
159
+ lease.close()
160
+ self._closed = True
161
+ self._http.close()
162
+ self._cloud.close()
163
+
164
+ def __enter__(self):
165
+ self._check_open()
166
+ return self
167
+
168
+ def __exit__(self, *args):
169
+ self.close()
170
+
171
+
172
+ class AsyncClient(AsyncDriver, BaseClient):
173
+ def __init__(
174
+ self,
175
+ *,
176
+ base_url,
177
+ token,
178
+ timeout=30,
179
+ max_retries=3,
180
+ file_concurrency=8,
181
+ upload_timeout=86400,
182
+ transport=None,
183
+ cloud_transport=None,
184
+ endpoint="auto",
185
+ ):
186
+ self._setup(base_url, token, max_retries, upload_timeout, endpoint)
187
+ if isinstance(file_concurrency, bool) or not isinstance(file_concurrency, int) or file_concurrency < 1:
188
+ raise ValidationError("file_concurrency must be positive")
189
+ self._file_concurrency = file_concurrency
190
+ self._http = httpx.AsyncClient(timeout=timeout, transport=transport, follow_redirects=False)
191
+ self._cloud = httpx.AsyncClient(
192
+ timeout=upload_timeout,
193
+ transport=cloud_transport,
194
+ limits=httpx.Limits(max_connections=file_concurrency),
195
+ follow_redirects=False,
196
+ )
197
+
198
+ async def close(self):
199
+ if not self._closed:
200
+ leases = list(self._leases)
201
+ for lease in leases:
202
+ lease.close()
203
+ for lease in leases:
204
+ await lease.wait()
205
+ if self._lease_tasks:
206
+ await asyncio.gather(*tuple(self._lease_tasks), return_exceptions=True)
207
+ self._closed = True
208
+ await self._http.aclose()
209
+ await self._cloud.aclose()
210
+
211
+ async def __aenter__(self):
212
+ self._check_open()
213
+ return self
214
+
215
+ async def __aexit__(self, *args):
216
+ await self.close()