omnigraph 0.14.0__py3-none-any.whl

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.
omnigraph/__init__.py ADDED
@@ -0,0 +1,55 @@
1
+ """Python client for the Omnigraph HTTP API (contract 0.14)."""
2
+
3
+ from ._client import Omnigraph
4
+ from ._errors import (
5
+ ApiContractError,
6
+ BadRequestError,
7
+ ConfigurationError,
8
+ ConflictError,
9
+ FailedDependencyError,
10
+ ForbiddenError,
11
+ GoneError,
12
+ GraphUnavailableError,
13
+ InternalServerError,
14
+ MethodNotAllowedError,
15
+ NetworkError,
16
+ NotFoundError,
17
+ OmnigraphError,
18
+ PayloadTooLargeError,
19
+ PreconditionFailedError,
20
+ RangeNotSatisfiableError,
21
+ RequestTimeoutError,
22
+ ServiceUnavailableError,
23
+ TooManyRequestsError,
24
+ UnauthorizedError,
25
+ UnsupportedMediaTypeError,
26
+ )
27
+ from ._version import HTTP_API_CONTRACT, HTTP_API_CONTRACT_HEADER, SERVER_VERSION
28
+
29
+ __all__ = [
30
+ "HTTP_API_CONTRACT",
31
+ "HTTP_API_CONTRACT_HEADER",
32
+ "SERVER_VERSION",
33
+ "ApiContractError",
34
+ "BadRequestError",
35
+ "ConfigurationError",
36
+ "ConflictError",
37
+ "FailedDependencyError",
38
+ "ForbiddenError",
39
+ "GoneError",
40
+ "GraphUnavailableError",
41
+ "InternalServerError",
42
+ "MethodNotAllowedError",
43
+ "NetworkError",
44
+ "NotFoundError",
45
+ "Omnigraph",
46
+ "OmnigraphError",
47
+ "PayloadTooLargeError",
48
+ "PreconditionFailedError",
49
+ "RangeNotSatisfiableError",
50
+ "RequestTimeoutError",
51
+ "ServiceUnavailableError",
52
+ "TooManyRequestsError",
53
+ "UnauthorizedError",
54
+ "UnsupportedMediaTypeError",
55
+ ]
omnigraph/_client.py ADDED
@@ -0,0 +1,327 @@
1
+ """The `Omnigraph` client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import types
6
+ from collections.abc import AsyncIterator, Sequence
7
+ from typing import Any, Self, cast
8
+
9
+ import httpx
10
+
11
+ from ._models import (
12
+ AccessOutput,
13
+ ChangeOutput,
14
+ DiffOutput,
15
+ GraphBatchLoadOutput,
16
+ HealthOutput,
17
+ IngestOutput,
18
+ LoadMode,
19
+ ReadinessOutput,
20
+ ReadOutput,
21
+ SnapshotOutput,
22
+ )
23
+ from ._receipts import valid_mutation_receipt
24
+ from ._resources import (
25
+ Blobs,
26
+ Branches,
27
+ Changes,
28
+ Cluster,
29
+ Commits,
30
+ Graphs,
31
+ Queries,
32
+ Schema,
33
+ _ndjson,
34
+ )
35
+ from ._transport import Transport
36
+
37
+
38
+ def _gq_body(
39
+ query: str,
40
+ *,
41
+ name: str | None,
42
+ params: dict[str, Any] | None,
43
+ branch: str | None,
44
+ ) -> dict[str, Any]:
45
+ body: dict[str, Any] = {"query": query}
46
+ if name is not None:
47
+ body["name"] = name
48
+ if params is not None:
49
+ body["params"] = params
50
+ if branch is not None:
51
+ body["branch"] = branch
52
+ return body
53
+
54
+
55
+ class Omnigraph:
56
+ """Async client for one `omnigraph-server`, optionally scoped to a graph.
57
+
58
+ ```python
59
+ async with Omnigraph("http://127.0.0.1:8080", graph_id="knowledge", token=...) as og:
60
+ result = await og.query("query q() { match { $p: Person } return { $p.name } }")
61
+ ```
62
+
63
+ `base_url` is the server root, including any proxy prefix. The client sends
64
+ `Omnigraph-Http-Api: 0.14` on every request, checks it on every response,
65
+ probes `HEAD /healthz` before data requests, follows no redirects, and never
66
+ retries.
67
+ """
68
+
69
+ def __init__(
70
+ self,
71
+ base_url: str,
72
+ *,
73
+ graph_id: str | None = None,
74
+ token: str | None = None,
75
+ timeout: float | httpx.Timeout = 30.0,
76
+ transport: httpx.AsyncBaseTransport | None = None,
77
+ ) -> None:
78
+ client = httpx.AsyncClient(
79
+ timeout=timeout, follow_redirects=False, transport=transport
80
+ )
81
+ self._init(
82
+ Transport(
83
+ base_url,
84
+ token=token,
85
+ graph_id=graph_id,
86
+ client=client,
87
+ owns_client=True,
88
+ )
89
+ )
90
+
91
+ def _init(self, transport: Transport) -> None:
92
+ self._t = transport
93
+ self.branches = Branches(transport)
94
+ self.commits = Commits(transport)
95
+ self.schema = Schema(transport)
96
+ self.graphs = Graphs(transport)
97
+ self.cluster = Cluster(transport)
98
+ self.queries = Queries(transport)
99
+ self.changes = Changes(transport)
100
+ self.blobs = Blobs(transport)
101
+
102
+ @property
103
+ def base_url(self) -> str:
104
+ return self._t.base_url
105
+
106
+ @property
107
+ def graph_id(self) -> str | None:
108
+ return self._t.graph_id
109
+
110
+ def graph(self, graph_id: str) -> Omnigraph:
111
+ """A client for another graph on the same server, sharing this client's
112
+ connection pool and credential. Close the original, not this one."""
113
+ scoped = object.__new__(Omnigraph)
114
+ scoped._init(self._t.scoped(graph_id))
115
+ return scoped
116
+
117
+ async def aclose(self) -> None:
118
+ await self._t.aclose()
119
+
120
+ async def __aenter__(self) -> Self:
121
+ return self
122
+
123
+ async def __aexit__(
124
+ self,
125
+ exc_type: type[BaseException] | None,
126
+ exc: BaseException | None,
127
+ tb: types.TracebackType | None,
128
+ ) -> None:
129
+ await self.aclose()
130
+
131
+ def __repr__(self) -> str:
132
+ return f"Omnigraph(base_url={self.base_url!r}, graph_id={self.graph_id!r})"
133
+
134
+ # -- probes --------------------------------------------------------------
135
+
136
+ async def health(self) -> HealthOutput:
137
+ """Liveness. Unauthenticated."""
138
+ return cast(HealthOutput, await self._t.request("GET", "/healthz"))
139
+
140
+ async def readiness(self) -> ReadinessOutput:
141
+ """Readiness. Both 200 and 503 return availability counts; check `ready`."""
142
+ return cast(
143
+ ReadinessOutput,
144
+ await self._t.request("GET", "/readyz", accepted_statuses=(503,)),
145
+ )
146
+
147
+ # -- graph-scoped ----------------------------------------------------------
148
+
149
+ async def access(
150
+ self,
151
+ *,
152
+ branch: str | None = None,
153
+ target_branch: str | None = None,
154
+ if_actor: str | None = None,
155
+ ) -> AccessOutput:
156
+ """The actions this credential may take, without exposing policy rules."""
157
+ return cast(
158
+ AccessOutput,
159
+ await self._t.request(
160
+ "GET",
161
+ "/access",
162
+ query={"branch": branch, "target_branch": target_branch},
163
+ if_actor=if_actor,
164
+ ),
165
+ )
166
+
167
+ async def query(
168
+ self,
169
+ query: str,
170
+ *,
171
+ name: str | None = None,
172
+ params: dict[str, Any] | None = None,
173
+ branch: str | None = None,
174
+ snapshot: str | None = None,
175
+ if_actor: str | None = None,
176
+ ) -> ReadOutput:
177
+ """Run a GQ read (`POST /query`). `params` keys match `$name` slots."""
178
+ body = _gq_body(query, name=name, params=params, branch=branch)
179
+ if snapshot is not None:
180
+ body["snapshot"] = snapshot
181
+ return cast(
182
+ ReadOutput,
183
+ await self._t.request("POST", "/query", body=body, if_actor=if_actor),
184
+ )
185
+
186
+ async def mutate(
187
+ self,
188
+ query: str,
189
+ *,
190
+ name: str | None = None,
191
+ params: dict[str, Any] | None = None,
192
+ branch: str | None = None,
193
+ if_graph_commit: str | None = None,
194
+ if_actor: str | None = None,
195
+ ) -> ChangeOutput:
196
+ """Run a GQ mutation (`POST /mutate`); its statements publish as one commit.
197
+
198
+ With `if_graph_commit` (a read's `graph_commit_id`) the dedicated
199
+ conditional route refuses a moved head with `PreconditionFailedError`;
200
+ it is never downgraded to an unconditional write. `commit: None` is a
201
+ successful no-op. A branch statement (`branch create|delete|merge …`)
202
+ names its own branches: send it without `name`, `params`, `branch`.
203
+ """
204
+ body = _gq_body(query, name=name, params=params, branch=branch)
205
+ if if_graph_commit is not None:
206
+ return cast(
207
+ ChangeOutput,
208
+ await self._t.request(
209
+ "POST",
210
+ "/mutate/if-graph-commit",
211
+ body=body,
212
+ headers={"Omnigraph-If-Graph-Commit": if_graph_commit},
213
+ if_actor=if_actor,
214
+ ),
215
+ )
216
+ result = await self._t.request("POST", "/mutate", body=body, if_actor=if_actor)
217
+ if not valid_mutation_receipt(result):
218
+ raise self._t.invalid_response(
219
+ "POST", "/mutate", "invalid branch merge receipt"
220
+ )
221
+ return cast(ChangeOutput, result)
222
+
223
+ async def snapshot(
224
+ self, *, branch: str | None = None, if_actor: str | None = None
225
+ ) -> SnapshotOutput:
226
+ """The latest commit's snapshot on a branch."""
227
+ return cast(
228
+ SnapshotOutput,
229
+ await self._t.request(
230
+ "GET", "/snapshot", query={"branch": branch}, if_actor=if_actor
231
+ ),
232
+ )
233
+
234
+ async def diff(
235
+ self,
236
+ from_: str,
237
+ to: str,
238
+ *,
239
+ page_token: str | None = None,
240
+ limit: int | None = None,
241
+ kind: Sequence[str] | None = None,
242
+ type: Sequence[str] | None = None,
243
+ op: Sequence[str] | None = None,
244
+ if_actor: str | None = None,
245
+ ) -> DiffOutput:
246
+ """One page of net entity changes between two branches or commits."""
247
+ return cast(
248
+ DiffOutput,
249
+ await self._t.request(
250
+ "GET",
251
+ "/diff",
252
+ query={
253
+ "from": from_,
254
+ "to": to,
255
+ "page_token": page_token,
256
+ "limit": None if limit is None else str(limit),
257
+ "kind": kind,
258
+ "type": type,
259
+ "op": op,
260
+ },
261
+ if_actor=if_actor,
262
+ ),
263
+ )
264
+
265
+ async def export(
266
+ self,
267
+ *,
268
+ branch: str | None = None,
269
+ type_names: Sequence[str] | None = None,
270
+ if_actor: str | None = None,
271
+ ) -> AsyncIterator[dict[str, Any]]:
272
+ """Stream a branch's nodes and edges as NDJSON records, without
273
+ buffering them. Breaking out of the loop cancels the download."""
274
+ body: dict[str, Any] = {}
275
+ if branch is not None:
276
+ body["branch"] = branch
277
+ if type_names is not None:
278
+ body["type_names"] = list(type_names)
279
+ async with self._t.stream(
280
+ "POST", "/export", body=body, if_actor=if_actor
281
+ ) as response:
282
+ async for record in _ndjson(response):
283
+ yield record
284
+
285
+ async def load_ndjson(
286
+ self,
287
+ ndjson: str | bytes,
288
+ *,
289
+ branch: str | None = None,
290
+ from_: str | None = None,
291
+ mode: LoadMode | None = None,
292
+ if_actor: str | None = None,
293
+ ) -> GraphBatchLoadOutput:
294
+ """Load one bounded NDJSON batch as one graph commit. Without `from_`
295
+ the branch must exist. `merge` upserts by key; it is not request
296
+ deduplication, so reconcile an ambiguous outcome before retrying."""
297
+ data = ndjson.encode() if isinstance(ndjson, str) else ndjson
298
+ return cast(
299
+ GraphBatchLoadOutput,
300
+ await self._t.request(
301
+ "POST",
302
+ "/load/ndjson",
303
+ content=data,
304
+ content_type="application/x-ndjson",
305
+ query={"branch": branch, "from": from_, "mode": mode},
306
+ if_actor=if_actor,
307
+ ),
308
+ )
309
+
310
+ async def load(
311
+ self,
312
+ data: str,
313
+ *,
314
+ branch: str | None = None,
315
+ from_: str | None = None,
316
+ mode: LoadMode | None = None,
317
+ if_actor: str | None = None,
318
+ ) -> IngestOutput:
319
+ """The compatibility JSON load (`POST /load`); prefer `load_ndjson`."""
320
+ body: dict[str, Any] = {"data": data}
321
+ for key, value in (("branch", branch), ("from", from_), ("mode", mode)):
322
+ if value is not None:
323
+ body[key] = value
324
+ return cast(
325
+ IngestOutput,
326
+ await self._t.request("POST", "/load", body=body, if_actor=if_actor),
327
+ )
omnigraph/_errors.py ADDED
@@ -0,0 +1,269 @@
1
+ """Typed errors. Catch the class you care about; every class carries the
2
+ server's `disposition` when the server sent one."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from typing import Any, cast
7
+
8
+ import httpx
9
+
10
+ from ._models import (
11
+ DispositionOutput,
12
+ ErrorCode,
13
+ ErrorOutput,
14
+ KeyConflictOutput,
15
+ MergeConflictOutput,
16
+ PreconditionFailureOutput,
17
+ ResourceLimitOutput,
18
+ )
19
+
20
+
21
+ class OmnigraphError(Exception):
22
+ """Base class. `status` is 0 when no HTTP response was received.
23
+
24
+ `request_dispatched` says whether the request may have reached the
25
+ server; `outcome_unknown` says a write may have taken effect, so the
26
+ caller must reconcile before deciding to retry.
27
+ """
28
+
29
+ status: int
30
+ code: ErrorCode | None
31
+ request_id: str | None
32
+ method: str
33
+ url: str
34
+ body: ErrorOutput | None
35
+ request_dispatched: bool
36
+ outcome_unknown: bool
37
+
38
+ def __init__(
39
+ self,
40
+ message: str,
41
+ *,
42
+ status: int = 0,
43
+ method: str,
44
+ url: str,
45
+ code: ErrorCode | None = None,
46
+ request_id: str | None = None,
47
+ body: ErrorOutput | None = None,
48
+ response: httpx.Response | None = None,
49
+ request_dispatched: bool = False,
50
+ outcome_unknown: bool = False,
51
+ ) -> None:
52
+ super().__init__(message)
53
+ self.message = message
54
+ self.status = status
55
+ self.code = code
56
+ self.request_id = request_id
57
+ self.method = method
58
+ self.url = url
59
+ self.body = body
60
+ self.response = response
61
+ self.request_dispatched = request_dispatched
62
+ self.outcome_unknown = outcome_unknown
63
+
64
+ @property
65
+ def disposition(self) -> DispositionOutput | None:
66
+ """What the server did and what to do next; absent after transport loss."""
67
+ return self.body.get("disposition") if self.body else None
68
+
69
+ @property
70
+ def retry_after(self) -> str | None:
71
+ """Server guidance for caller-bounded retries of refused requests."""
72
+ return self.response.headers.get("Retry-After") if self.response else None
73
+
74
+ def __repr__(self) -> str:
75
+ return (
76
+ f"{type(self).__name__}(status={self.status}, code={self.code!r}, "
77
+ f"message={self.message!r})"
78
+ )
79
+
80
+
81
+ class BadRequestError(OmnigraphError):
82
+ pass
83
+
84
+
85
+ class UnauthorizedError(OmnigraphError):
86
+ pass
87
+
88
+
89
+ class ForbiddenError(OmnigraphError):
90
+ pass
91
+
92
+
93
+ class NotFoundError(OmnigraphError):
94
+ pass
95
+
96
+
97
+ class MethodNotAllowedError(OmnigraphError):
98
+ pass
99
+
100
+
101
+ class RequestTimeoutError(OmnigraphError):
102
+ pass
103
+
104
+
105
+ class UnsupportedMediaTypeError(OmnigraphError):
106
+ pass
107
+
108
+
109
+ class ConflictError(OmnigraphError):
110
+ @property
111
+ def merge_conflicts(self) -> list[MergeConflictOutput]:
112
+ return list(self.body.get("merge_conflicts") or []) if self.body else []
113
+
114
+ @property
115
+ def key_conflict(self) -> KeyConflictOutput | None:
116
+ return self.body.get("key_conflict") if self.body else None
117
+
118
+
119
+ class GoneError(OmnigraphError):
120
+ """Retained change history is unavailable; recover through a baseline."""
121
+
122
+
123
+ class PreconditionFailedError(OmnigraphError):
124
+ """A stale graph-head precondition, an actor mismatch, or a failed Blob If-Match."""
125
+
126
+ @property
127
+ def precondition_failure(self) -> PreconditionFailureOutput | None:
128
+ return self.body.get("precondition_failure") if self.body else None
129
+
130
+
131
+ class PayloadTooLargeError(OmnigraphError):
132
+ @property
133
+ def resource_limit(self) -> ResourceLimitOutput | None:
134
+ return self.body.get("resource_limit") if self.body else None
135
+
136
+
137
+ class RangeNotSatisfiableError(OmnigraphError):
138
+ pass
139
+
140
+
141
+ class FailedDependencyError(OmnigraphError):
142
+ pass
143
+
144
+
145
+ class TooManyRequestsError(OmnigraphError):
146
+ pass
147
+
148
+
149
+ class InternalServerError(OmnigraphError):
150
+ pass
151
+
152
+
153
+ class ServiceUnavailableError(OmnigraphError):
154
+ pass
155
+
156
+
157
+ class GraphUnavailableError(ServiceUnavailableError):
158
+ pass
159
+
160
+
161
+ class NetworkError(OmnigraphError):
162
+ """The transport failed, or the response body was interrupted or invalid."""
163
+
164
+
165
+ class ApiContractError(OmnigraphError):
166
+ """Discovery failed, or a response lacked the expected HTTP contract header."""
167
+
168
+
169
+ class ConfigurationError(OmnigraphError):
170
+ """Invalid client configuration; no request was sent."""
171
+
172
+
173
+ _BY_STATUS: dict[int, type[OmnigraphError]] = {
174
+ 400: BadRequestError,
175
+ 401: UnauthorizedError,
176
+ 403: ForbiddenError,
177
+ 404: NotFoundError,
178
+ 405: MethodNotAllowedError,
179
+ 408: RequestTimeoutError,
180
+ 409: ConflictError,
181
+ 410: GoneError,
182
+ 412: PreconditionFailedError,
183
+ 413: PayloadTooLargeError,
184
+ 415: UnsupportedMediaTypeError,
185
+ 416: RangeNotSatisfiableError,
186
+ 424: FailedDependencyError,
187
+ 429: TooManyRequestsError,
188
+ 500: InternalServerError,
189
+ 503: ServiceUnavailableError,
190
+ }
191
+
192
+ _BY_CODE: dict[str, type[OmnigraphError]] = {
193
+ "bad_request": BadRequestError,
194
+ "api_contract_mismatch": ApiContractError,
195
+ "service_unavailable": ServiceUnavailableError,
196
+ "graph_unavailable": GraphUnavailableError,
197
+ "unauthorized": UnauthorizedError,
198
+ "forbidden": ForbiddenError,
199
+ "not_found": NotFoundError,
200
+ "method_not_allowed": MethodNotAllowedError,
201
+ "conflict": ConflictError,
202
+ "too_many_requests": TooManyRequestsError,
203
+ "internal": InternalServerError,
204
+ "actor_mismatch": PreconditionFailedError,
205
+ "outcome_unknown": InternalServerError,
206
+ "precondition_failed": PreconditionFailedError,
207
+ "recovery_required": ServiceUnavailableError,
208
+ "external_blob_source": FailedDependencyError,
209
+ "change_feed_gap": GoneError,
210
+ "request_timeout": RequestTimeoutError,
211
+ "branch_start_refusal": ConflictError,
212
+ "unattached_cannot_publish": ConflictError,
213
+ "payload_too_large": PayloadTooLargeError,
214
+ "unsupported_media_type": UnsupportedMediaTypeError,
215
+ "range_not_satisfiable": RangeNotSatisfiableError,
216
+ "cancelled": BadRequestError,
217
+ "deadline_exceeded": BadRequestError,
218
+ "result_too_large": PayloadTooLargeError,
219
+ }
220
+
221
+
222
+ def error_body(parsed: Any) -> ErrorOutput | None:
223
+ """The parsed body when it is the server's error envelope, else `None`."""
224
+ if not isinstance(parsed, dict):
225
+ return None
226
+ disposition = parsed.get("disposition")
227
+ if not (
228
+ isinstance(parsed.get("error"), str)
229
+ and isinstance(parsed.get("code"), str)
230
+ and isinstance(disposition, dict)
231
+ and isinstance(disposition.get("effects"), str)
232
+ and isinstance(disposition.get("action"), str)
233
+ ):
234
+ return None
235
+ return cast(ErrorOutput, parsed)
236
+
237
+
238
+ def from_response(
239
+ response: httpx.Response,
240
+ body: ErrorOutput | None,
241
+ *,
242
+ method: str,
243
+ url: str,
244
+ may_write: bool,
245
+ ) -> OmnigraphError:
246
+ code = body["code"] if body else None
247
+ if code == "graph_unavailable":
248
+ cls: type[OmnigraphError] = GraphUnavailableError
249
+ elif code == "api_contract_mismatch":
250
+ cls = ApiContractError
251
+ else:
252
+ cls = (
253
+ _BY_STATUS.get(response.status_code)
254
+ or (_BY_CODE.get(code) if code else None)
255
+ or InternalServerError
256
+ )
257
+ effects = body["disposition"]["effects"] if body else None
258
+ return cls(
259
+ body["error"] if body else f"HTTP {response.status_code}",
260
+ status=response.status_code,
261
+ method=method,
262
+ url=url,
263
+ code=code,
264
+ request_id=response.headers.get("X-Request-Id"),
265
+ body=body,
266
+ response=response,
267
+ request_dispatched=True,
268
+ outcome_unknown=may_write and effects != "none",
269
+ )