nucladb 0.3.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.
nucladb/__init__.py ADDED
@@ -0,0 +1,21 @@
1
+ from .client import APIKey, Client, DistanceMetric, ScoredVector, Tenant
2
+ from .errors import (
3
+ AlreadyExists,
4
+ FailedPrecondition,
5
+ InvalidArgument,
6
+ NotFound,
7
+ NucladbError,
8
+ PermissionDenied,
9
+ QuotaExceeded,
10
+ RateLimited,
11
+ RestError,
12
+ Unauthenticated,
13
+ Unavailable,
14
+ )
15
+ from .rest import RestClient
16
+
17
+ __all__ = [
18
+ "APIKey", "AlreadyExists", "Client", "DistanceMetric", "FailedPrecondition", "InvalidArgument",
19
+ "NotFound", "NucladbError", "PermissionDenied", "QuotaExceeded", "RateLimited", "RestClient",
20
+ "RestError", "ScoredVector", "Tenant", "Unauthenticated", "Unavailable",
21
+ ]
nucladb/cli.py ADDED
@@ -0,0 +1,175 @@
1
+ """`nucladb`: a thin command-line client over this package's own Client,
2
+ mirroring cmd/nucladb-cli's commands and semantics (see docs/cli.md in
3
+ the main repo) so anyone who's used the Go CLI already knows this one.
4
+ Installed as a single console-script entry point (see pyproject.toml)
5
+ so `pip install nucladb` (or `pipx install nucladb`) is enough to get
6
+ the `nucladb` command on PATH — no separate build step.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ import sys
15
+
16
+ import grpc
17
+ from grpc_health.v1 import health_pb2, health_pb2_grpc
18
+
19
+ from .client import Client, DistanceMetric
20
+ from .errors import NucladbError
21
+
22
+ DEFAULT_ADDR = os.environ.get("NUCLADB_ADDR", "localhost:9090")
23
+
24
+ _METRICS = {
25
+ "cosine": DistanceMetric.COSINE,
26
+ "l2": DistanceMetric.L2,
27
+ "dot": DistanceMetric.DOT,
28
+ }
29
+
30
+
31
+ def _parse_vector(s: str) -> list[float]:
32
+ return [float(x) for x in s.split(",")]
33
+
34
+
35
+ def _parse_meta(pairs: list[str] | None) -> dict[str, str]:
36
+ meta = {}
37
+ for pair in pairs or []:
38
+ key, _, value = pair.partition("=")
39
+ meta[key] = value
40
+ return meta
41
+
42
+
43
+ def cmd_ping(client: Client, args: argparse.Namespace) -> None:
44
+ stub = health_pb2_grpc.HealthStub(client.channel)
45
+ resp = stub.Check(health_pb2.HealthCheckRequest())
46
+ if resp.status == health_pb2.HealthCheckResponse.SERVING:
47
+ print("ok")
48
+ else:
49
+ print(f"not serving: {health_pb2.HealthCheckResponse.ServingStatus.Name(resp.status)}")
50
+ sys.exit(1)
51
+
52
+
53
+ def cmd_create_tenant(client: Client, args: argparse.Namespace) -> None:
54
+ client.create_tenant(args.id, max_vectors=args.max_vectors, max_qps=args.max_qps)
55
+ print(f'created tenant "{args.id}"')
56
+
57
+
58
+ def cmd_insert(client: Client, args: argparse.Namespace) -> None:
59
+ id_ = client.insert(args.id, _parse_vector(args.vector), _parse_meta(args.meta))
60
+ print(f"inserted id={id_}")
61
+
62
+
63
+ def cmd_batch_upsert(client: Client, args: argparse.Namespace) -> None:
64
+ with open(args.file) as f:
65
+ items = json.load(f)
66
+ vectors = [
67
+ (item["id"], item["values"], item.get("metadata")) for item in items
68
+ ]
69
+ n = client.batch_upsert(vectors)
70
+ print(f"upserted {n} vectors")
71
+
72
+
73
+ def cmd_search(client: Client, args: argparse.Namespace) -> None:
74
+ metric = _METRICS.get(args.metric, DistanceMetric.UNSPECIFIED) if args.metric else DistanceMetric.UNSPECIFIED
75
+ results = client.search(
76
+ _parse_vector(args.vector),
77
+ top_k=args.top_k,
78
+ metric=metric,
79
+ ef_search=args.ef or 0,
80
+ filters=_parse_meta(args.filter),
81
+ )
82
+ for r in results:
83
+ print(f"{r.id}\tscore={r.score:.6f}\t{r.metadata}")
84
+
85
+
86
+ def cmd_delete(client: Client, args: argparse.Namespace) -> None:
87
+ deleted = client.delete(args.id)
88
+ print(f"deleted={str(deleted).lower()}")
89
+
90
+
91
+ def cmd_get(client: Client, args: argparse.Namespace) -> None:
92
+ got = client.get(args.id)
93
+ if got is None:
94
+ print(f"nucladb: {args.id} not found", file=sys.stderr)
95
+ sys.exit(1)
96
+ vector, metadata = got
97
+ print(f"{args.id}\t{','.join(f'{v:g}' for v in vector)}\t{metadata}")
98
+
99
+
100
+ def cmd_list(client: Client, args: argparse.Namespace) -> None:
101
+ for id in client.list():
102
+ print(id)
103
+
104
+
105
+ def cmd_count(client: Client, args: argparse.Namespace) -> None:
106
+ print(client.count())
107
+
108
+
109
+ def build_parser() -> argparse.ArgumentParser:
110
+ p = argparse.ArgumentParser(prog="nucladb", description="NuclaDB command-line client")
111
+ p.add_argument("--addr", default=DEFAULT_ADDR, help=f"server address (default: {DEFAULT_ADDR}, or $NUCLADB_ADDR)")
112
+ p.add_argument("--tenant", default="", help="tenant id (default: the reserved 'default' tenant)")
113
+ sub = p.add_subparsers(dest="command", required=True)
114
+
115
+ sub.add_parser("ping", help="check the server is reachable").set_defaults(func=cmd_ping)
116
+
117
+ ct = sub.add_parser("create-tenant", help="provision a new isolated tenant")
118
+ ct.add_argument("--id", required=True)
119
+ ct.add_argument("--max-vectors", type=int, default=0)
120
+ ct.add_argument("--max-qps", type=float, default=0)
121
+ ct.set_defaults(func=cmd_create_tenant)
122
+
123
+ ins = sub.add_parser("insert", help="insert or update a single vector")
124
+ ins.add_argument("--id", required=True)
125
+ ins.add_argument("--vector", required=True, help="comma-separated floats, e.g. 0.1,0.2,0.3")
126
+ ins.add_argument("--meta", action="append", help="key=value metadata pair; repeat for more")
127
+ ins.set_defaults(func=cmd_insert)
128
+
129
+ bu = sub.add_parser("batch-upsert", help="insert or update many vectors from a JSON file")
130
+ bu.add_argument("--file", required=True, help='JSON array of {"id", "values", "metadata"}')
131
+ bu.set_defaults(func=cmd_batch_upsert)
132
+
133
+ se = sub.add_parser("search", help="find the nearest neighbors of a query vector")
134
+ se.add_argument("--vector", required=True)
135
+ se.add_argument("--top-k", type=int, default=10)
136
+ se.add_argument("--ef", type=int, default=0, help="candidate beam width (default: top-k)")
137
+ se.add_argument("--metric", choices=sorted(_METRICS), default=None)
138
+ se.add_argument("--filter", action="append", help="key=value metadata filter; repeat for AND")
139
+ se.set_defaults(func=cmd_search)
140
+
141
+ de = sub.add_parser("delete", help="delete a vector by id (idempotent)")
142
+ de.add_argument("--id", required=True)
143
+ de.set_defaults(func=cmd_delete)
144
+
145
+ ge = sub.add_parser("get", help="print one vector and its metadata")
146
+ ge.add_argument("--id", required=True)
147
+ ge.set_defaults(func=cmd_get)
148
+
149
+ sub.add_parser("list", help="print every stored id").set_defaults(func=cmd_list)
150
+ sub.add_parser("count", help="print how many vectors are stored").set_defaults(func=cmd_count)
151
+
152
+ return p
153
+
154
+
155
+ def main() -> None:
156
+ args = build_parser().parse_args()
157
+ with Client(
158
+ args.addr,
159
+ tenant_id=args.tenant,
160
+ api_key=os.environ.get("NUCLADB_API_KEY", ""),
161
+ tls=os.environ.get("NUCLADB_TLS") == "1",
162
+ ca_file=os.environ.get("NUCLADB_CA", ""),
163
+ ) as client:
164
+ try:
165
+ args.func(client, args)
166
+ except NucladbError as e:
167
+ print(f"nucladb: {e.message}", file=sys.stderr)
168
+ sys.exit(1)
169
+ except grpc.RpcError as e: # the health check isn't a NuclaDB call
170
+ print(f"nucladb: {e.code()}: {e.details()}", file=sys.stderr)
171
+ sys.exit(1)
172
+
173
+
174
+ if __name__ == "__main__":
175
+ main()
nucladb/client.py ADDED
@@ -0,0 +1,341 @@
1
+ """A thin, pythonic wrapper around the generated NuclaDB gRPC stubs.
2
+
3
+ Every data method maps 1:1 onto one RPC in proto/nucladb.proto — this
4
+ package adds ergonomics (a context manager, plain dicts/lists instead of
5
+ protobuf messages, keyword defaults matching the server's own), not new
6
+ behavior. See the Go CLI (cmd/nucladb-cli, docs/cli.md) for the same API
7
+ surface from the reference implementation's own side.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import warnings
13
+ from dataclasses import dataclass
14
+ from enum import IntEnum
15
+ from typing import Iterable
16
+
17
+ import grpc
18
+
19
+ from . import nucladb_pb2 as pb
20
+ from . import nucladb_pb2_grpc as pb_grpc
21
+ from .errors import NotFound, error_for
22
+
23
+
24
+ class DistanceMetric(IntEnum):
25
+ UNSPECIFIED = pb.DISTANCE_METRIC_UNSPECIFIED
26
+ COSINE = pb.DISTANCE_METRIC_COSINE
27
+ L2 = pb.DISTANCE_METRIC_L2
28
+ DOT = pb.DISTANCE_METRIC_DOT
29
+
30
+
31
+ _FILTER_OPS = {
32
+ "eq": pb.FILTER_OP_EQ,
33
+ "ne": pb.FILTER_OP_NE,
34
+ "in": pb.FILTER_OP_IN,
35
+ "not_in": pb.FILTER_OP_NOT_IN,
36
+ "gt": pb.FILTER_OP_GT,
37
+ "gte": pb.FILTER_OP_GTE,
38
+ "lt": pb.FILTER_OP_LT,
39
+ "lte": pb.FILTER_OP_LTE,
40
+ "exists": pb.FILTER_OP_EXISTS,
41
+ }
42
+
43
+
44
+ @dataclass
45
+ class Tenant:
46
+ id: str
47
+ vector_count: int
48
+ max_vectors: int
49
+ max_qps: float
50
+ dim: int
51
+ metric: DistanceMetric
52
+ index: str = "hnsw"
53
+ # Set when the server couldn't open this tenant's files; its data calls
54
+ # fail with FailedPrecondition until they are repaired.
55
+ open_error: str = ""
56
+
57
+ @property
58
+ def tenant_id(self) -> str:
59
+ """The same as id, under the name the API uses."""
60
+ return self.id
61
+
62
+
63
+ @dataclass
64
+ class APIKey:
65
+ """An issued API key's details. The key itself is only ever returned
66
+ by create_api_key."""
67
+
68
+ id: str
69
+ name: str
70
+ tenants: list[str]
71
+ admin: bool
72
+ created_unix: int
73
+ expires_unix: int # 0: never
74
+
75
+
76
+ def _api_key(k) -> APIKey:
77
+ return APIKey(
78
+ id=k.id,
79
+ name=k.name,
80
+ tenants=list(k.tenants),
81
+ admin=k.admin,
82
+ created_unix=k.created_unix,
83
+ expires_unix=k.expires_unix,
84
+ )
85
+
86
+
87
+ @dataclass
88
+ class ScoredVector:
89
+ id: str
90
+ score: float
91
+ metadata: dict[str, str]
92
+
93
+
94
+ class _Defaults(grpc.UnaryUnaryClientInterceptor):
95
+ """Adds the API key, if any, and a deadline to every call."""
96
+
97
+ def __init__(self, key: str, timeout: float | None):
98
+ self._metadata = (("authorization", "Bearer " + key),) if key else ()
99
+ self._timeout = timeout
100
+
101
+ def intercept_unary_unary(self, continuation, details, request):
102
+ details = details._replace(
103
+ metadata=tuple(details.metadata or ()) + self._metadata,
104
+ timeout=details.timeout if details.timeout is not None else self._timeout,
105
+ )
106
+ outcome = continuation(details, request)
107
+ if outcome.code() != grpc.StatusCode.OK:
108
+ raise error_for(outcome.code().name, outcome.details() or "") from None
109
+ return outcome
110
+
111
+
112
+ def _is_local(address: str) -> bool:
113
+ host = address.rsplit(":", 1)[0].strip("[]")
114
+ return host in ("localhost", "127.0.0.1", "::1") or address.startswith("unix:")
115
+
116
+
117
+ class Client:
118
+ """A connection to one NuclaDB server. Use as a context manager:
119
+
120
+ with Client("localhost:9090") as db:
121
+ db.insert("v1", [0.1, 0.2, 0.3])
122
+ db.search([0.1, 0.2, 0.3], top_k=5)
123
+ """
124
+
125
+ def __init__(
126
+ self,
127
+ address: str,
128
+ tenant_id: str = "",
129
+ api_key: str = "",
130
+ tls: bool = False,
131
+ timeout: float | None = 30,
132
+ ca_file: str = "",
133
+ ):
134
+ """timeout is each call's deadline in seconds; None waits forever.
135
+ ca_file trusts that CA certificate instead of the system's, such as a
136
+ cluster's ca.pem, and turns TLS on."""
137
+ self.tenant_id = tenant_id
138
+ if ca_file:
139
+ with open(ca_file, "rb") as f:
140
+ creds = grpc.ssl_channel_credentials(root_certificates=f.read())
141
+ self.channel = grpc.secure_channel(address, creds)
142
+ elif tls:
143
+ self.channel = grpc.secure_channel(address, grpc.ssl_channel_credentials())
144
+ else:
145
+ if api_key and not _is_local(address):
146
+ warnings.warn(
147
+ f"sending an API key to {address} without TLS; anyone on the path can read it. "
148
+ "Pass tls=True (or set NUCLADB_TLS=1).",
149
+ stacklevel=2,
150
+ )
151
+ self.channel = grpc.insecure_channel(address)
152
+ channel = grpc.intercept_channel(self.channel, _Defaults(api_key, timeout))
153
+ self._stub = pb_grpc.NuclaDBStub(channel)
154
+
155
+ def __enter__(self) -> "Client":
156
+ return self
157
+
158
+ def __exit__(self, *exc_info) -> None:
159
+ self.close()
160
+
161
+ def close(self) -> None:
162
+ self.channel.close()
163
+
164
+ def create_tenant(
165
+ self,
166
+ tenant_id: str,
167
+ max_vectors: int = 0,
168
+ max_qps: float = 0,
169
+ dim: int = 0,
170
+ metric: DistanceMetric = DistanceMetric.UNSPECIFIED,
171
+ index: str = "",
172
+ ) -> None:
173
+ """dim, metric and index ("hnsw", "sq8" or "pq") default to the server's
174
+ -dim, -metric and -index."""
175
+ self._stub.CreateTenant(
176
+ pb.CreateTenantRequest(
177
+ tenant_id=tenant_id,
178
+ quota=pb.TenantQuota(max_vectors=max_vectors, max_qps=max_qps),
179
+ dim=dim,
180
+ metric=int(metric),
181
+ index=index,
182
+ )
183
+ )
184
+
185
+ def list_tenants(self) -> list[Tenant]:
186
+ resp = self._stub.ListTenants(pb.ListTenantsRequest())
187
+ return [
188
+ Tenant(
189
+ id=t.tenant_id,
190
+ vector_count=t.vector_count,
191
+ max_vectors=t.quota.max_vectors,
192
+ max_qps=t.quota.max_qps,
193
+ dim=t.dim,
194
+ metric=DistanceMetric(t.metric),
195
+ index=t.index or "hnsw",
196
+ open_error=t.open_error,
197
+ )
198
+ for t in resp.tenants
199
+ ]
200
+
201
+ def delete_tenant(self, tenant_id: str) -> None:
202
+ self._stub.DeleteTenant(pb.DeleteTenantRequest(tenant_id=tenant_id))
203
+
204
+ def set_quota(self, tenant_id: str, max_vectors: int = 0, max_qps: float = 0) -> None:
205
+ self._stub.SetQuota(
206
+ pb.SetQuotaRequest(
207
+ tenant_id=tenant_id,
208
+ quota=pb.TenantQuota(max_vectors=max_vectors, max_qps=max_qps),
209
+ )
210
+ )
211
+
212
+ def create_api_key(
213
+ self,
214
+ tenants: list[str] | None = None,
215
+ name: str = "",
216
+ admin: bool = False,
217
+ ttl_seconds: int = 0,
218
+ ) -> tuple[str, APIKey]:
219
+ """Issues a key (needs an admin key) and returns it with its details.
220
+ This is the only time the key is available; the server keeps a hash.
221
+ ttl_seconds 0 means it never expires."""
222
+ resp = self._stub.CreateAPIKey(
223
+ pb.CreateAPIKeyRequest(
224
+ name=name, tenants=tenants or [], admin=admin, ttl_seconds=ttl_seconds
225
+ )
226
+ )
227
+ return resp.key, _api_key(resp.info)
228
+
229
+ def list_api_keys(self) -> list[APIKey]:
230
+ return [_api_key(k) for k in self._stub.ListAPIKeys(pb.ListAPIKeysRequest()).keys]
231
+
232
+ def revoke_api_key(self, id: str) -> None:
233
+ self._stub.RevokeAPIKey(pb.RevokeAPIKeyRequest(id=id))
234
+
235
+ def insert(
236
+ self, id: str, vector: list[float], metadata: dict[str, str] | None = None
237
+ ) -> str:
238
+ resp = self._stub.Insert(
239
+ pb.InsertRequest(vector=self._vector(id, vector, metadata))
240
+ )
241
+ return resp.id
242
+
243
+ def batch_upsert(
244
+ self, vectors: Iterable[tuple[str, list[float], dict[str, str] | None]]
245
+ ) -> int:
246
+ """vectors is an iterable of (id, vector, metadata) tuples."""
247
+ resp = self._stub.BatchUpsert(
248
+ pb.BatchUpsertRequest(
249
+ vectors=[self._vector(id, v, meta) for id, v, meta in vectors]
250
+ )
251
+ )
252
+ return resp.upserted
253
+
254
+ def delete(self, id: str) -> bool:
255
+ # deletes are idempotent by design (see internal/engine/engine.go's
256
+ # Delete doc comment) — deleting an unknown or already-deleted id
257
+ # is not an error; deleted is False when there was nothing to delete.
258
+ resp = self._stub.Delete(
259
+ pb.DeleteRequest(id=id, tenant_id=self.tenant_id)
260
+ )
261
+ return resp.deleted
262
+
263
+ def get(self, id: str) -> tuple[list[float], dict[str, str]] | None:
264
+ """Returns (vector, metadata), or None if id isn't stored."""
265
+ try:
266
+ resp = self._stub.Get(pb.GetRequest(id=id, tenant_id=self.tenant_id))
267
+ except NotFound as e:
268
+ if "tenant not found" not in e.message:
269
+ return None
270
+ raise
271
+ return list(resp.vector.values), dict(resp.vector.metadata)
272
+
273
+ def update_metadata(self, id: str, metadata: dict[str, str]) -> None:
274
+ """Replaces id's metadata without touching its vector."""
275
+ self._stub.UpdateMetadata(
276
+ pb.UpdateMetadataRequest(id=id, metadata=metadata, tenant_id=self.tenant_id)
277
+ )
278
+
279
+ def list(self, page_size: int = 0) -> Iterable[str]:
280
+ """Yields every stored id, fetching a page at a time."""
281
+ token = ""
282
+ while True:
283
+ resp = self._stub.List(
284
+ pb.ListRequest(tenant_id=self.tenant_id, page_token=token, page_size=page_size)
285
+ )
286
+ yield from resp.ids
287
+ token = resp.next_page_token
288
+ if not token:
289
+ return
290
+
291
+ def count(self) -> int:
292
+ return self._stub.Count(pb.CountRequest(tenant_id=self.tenant_id)).count
293
+
294
+ def search(
295
+ self,
296
+ query: list[float],
297
+ top_k: int = 10,
298
+ metric: DistanceMetric = DistanceMetric.UNSPECIFIED,
299
+ ef_search: int = 0,
300
+ filters: dict[str, str] | None = None,
301
+ where: Iterable[tuple] = (),
302
+ ) -> list[ScoredVector]:
303
+ """filters are key=value matches. where takes (key, op) or
304
+ (key, op, value) tuples, op one of eq, ne, in, not_in, gt, gte, lt,
305
+ lte, exists; value is a list for in and not_in. Every filter has
306
+ to match."""
307
+ clauses = [pb.MetadataFilter(key=k, value=v) for k, v in (filters or {}).items()]
308
+ for key, op, *rest in where:
309
+ if op not in _FILTER_OPS:
310
+ raise ValueError(f"unknown filter op {op!r}")
311
+ value = rest[0] if rest else None
312
+ clause = pb.MetadataFilter(key=key, op=_FILTER_OPS[op])
313
+ if isinstance(value, (list, tuple)):
314
+ clause.values.extend(str(v) for v in value)
315
+ elif value is not None:
316
+ clause.value = str(value)
317
+ clauses.append(clause)
318
+ resp = self._stub.Search(
319
+ pb.SearchRequest(
320
+ query=query,
321
+ top_k=top_k,
322
+ metric=int(metric),
323
+ ef_search=ef_search,
324
+ filters=clauses,
325
+ tenant_id=self.tenant_id,
326
+ )
327
+ )
328
+ return [
329
+ ScoredVector(id=m.id, score=m.score, metadata=dict(m.metadata))
330
+ for m in resp.matches
331
+ ]
332
+
333
+ def _vector(
334
+ self, id: str, values: list[float], metadata: dict[str, str] | None
335
+ ) -> pb.Vector:
336
+ return pb.Vector(
337
+ id=id,
338
+ values=values,
339
+ metadata=metadata or {},
340
+ tenant_id=self.tenant_id,
341
+ )
nucladb/errors.py ADDED
@@ -0,0 +1,91 @@
1
+ """Errors raised by Client and RestClient.
2
+
3
+ Every error the server returns is a NucladbError, or one of the
4
+ subclasses below, so callers can catch the case they handle:
5
+
6
+ try:
7
+ db.insert("1", vector)
8
+ except nucladb.QuotaExceeded:
9
+ ...
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+
15
+ class NucladbError(Exception):
16
+ """A call the server refused or couldn't answer.
17
+
18
+ code is the gRPC status name, such as "NOT_FOUND"; message is the
19
+ server's explanation; status is the HTTP status for RestClient calls
20
+ and None for Client calls.
21
+ """
22
+
23
+ def __init__(self, code: str, message: str, status: int | None = None):
24
+ super().__init__(f"{code}: {message}" if status is None else f"HTTP {status} {code}: {message}")
25
+ self.code = code
26
+ self.message = message
27
+ self.status = status
28
+
29
+
30
+ class InvalidArgument(NucladbError):
31
+ """The request is malformed: a wrong vector length, a bad filter, an unknown field."""
32
+
33
+
34
+ class NotFound(NucladbError):
35
+ """The tenant or vector doesn't exist."""
36
+
37
+
38
+ class AlreadyExists(NucladbError):
39
+ """A tenant with that id already exists."""
40
+
41
+
42
+ class Unauthenticated(NucladbError):
43
+ """The server needs an API key and got none, or an unknown or expired one."""
44
+
45
+
46
+ class PermissionDenied(NucladbError):
47
+ """The API key doesn't cover this tenant or operation."""
48
+
49
+
50
+ class FailedPrecondition(NucladbError):
51
+ """The tenant can't take this request in its current state; retrying won't help."""
52
+
53
+
54
+ class QuotaExceeded(FailedPrecondition):
55
+ """The tenant is at its max_vectors; delete vectors or raise the quota."""
56
+
57
+
58
+ class RateLimited(NucladbError):
59
+ """The tenant is over its max_qps; retrying after a moment will work."""
60
+
61
+
62
+ class Unavailable(NucladbError):
63
+ """The server, or the part of a cluster holding the data, can't be reached.
64
+
65
+ For a write, the outcome is unknown: it may or may not have been
66
+ applied. Upserts are idempotent, so retrying is safe.
67
+ """
68
+
69
+
70
+ _BY_CODE = {
71
+ "INVALID_ARGUMENT": InvalidArgument,
72
+ "NOT_FOUND": NotFound,
73
+ "ALREADY_EXISTS": AlreadyExists,
74
+ "UNAUTHENTICATED": Unauthenticated,
75
+ "PERMISSION_DENIED": PermissionDenied,
76
+ "FAILED_PRECONDITION": FailedPrecondition,
77
+ "RESOURCE_EXHAUSTED": RateLimited,
78
+ "UNAVAILABLE": Unavailable,
79
+ }
80
+
81
+
82
+ def error_for(code: str, message: str, status: int | None = None) -> NucladbError:
83
+ """The NucladbError subclass for a gRPC status name."""
84
+ cls = _BY_CODE.get(code, NucladbError)
85
+ if cls is FailedPrecondition and "quota" in message:
86
+ cls = QuotaExceeded
87
+ return cls(code, message, status)
88
+
89
+
90
+ # Before 0.3, RestClient raised RestError; it is the same class now.
91
+ RestError = NucladbError