rustegon 0.1.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 (66) hide show
  1. rustegon-0.1.0/.gitignore +7 -0
  2. rustegon-0.1.0/PKG-INFO +90 -0
  3. rustegon-0.1.0/README.md +69 -0
  4. rustegon-0.1.0/pyproject.toml +101 -0
  5. rustegon-0.1.0/src/rustegon/__init__.py +129 -0
  6. rustegon-0.1.0/src/rustegon/_decimal128.py +102 -0
  7. rustegon-0.1.0/src/rustegon/_error_table.py +83 -0
  8. rustegon-0.1.0/src/rustegon/_ops.py +591 -0
  9. rustegon-0.1.0/src/rustegon/_pb/__init__.py +3 -0
  10. rustegon-0.1.0/src/rustegon/_pb/admin_pb2.py +117 -0
  11. rustegon-0.1.0/src/rustegon/_pb/admin_pb2.pyi +1077 -0
  12. rustegon-0.1.0/src/rustegon/_pb/admin_pb2_grpc.py +767 -0
  13. rustegon-0.1.0/src/rustegon/_pb/admin_pb2_grpc.pyi +249 -0
  14. rustegon-0.1.0/src/rustegon/_pb/auth_pb2.py +55 -0
  15. rustegon-0.1.0/src/rustegon/_pb/auth_pb2.pyi +274 -0
  16. rustegon-0.1.0/src/rustegon/_pb/auth_pb2_grpc.py +219 -0
  17. rustegon-0.1.0/src/rustegon/_pb/auth_pb2_grpc.pyi +117 -0
  18. rustegon-0.1.0/src/rustegon/_pb/backup_pb2.py +94 -0
  19. rustegon-0.1.0/src/rustegon/_pb/backup_pb2.pyi +858 -0
  20. rustegon-0.1.0/src/rustegon/_pb/backup_pb2_grpc.py +476 -0
  21. rustegon-0.1.0/src/rustegon/_pb/backup_pb2_grpc.pyi +192 -0
  22. rustegon-0.1.0/src/rustegon/_pb/common_pb2.py +52 -0
  23. rustegon-0.1.0/src/rustegon/_pb/common_pb2.pyi +243 -0
  24. rustegon-0.1.0/src/rustegon/_pb/common_pb2_grpc.py +24 -0
  25. rustegon-0.1.0/src/rustegon/_pb/common_pb2_grpc.pyi +22 -0
  26. rustegon-0.1.0/src/rustegon/_pb/document_pb2.py +99 -0
  27. rustegon-0.1.0/src/rustegon/_pb/document_pb2.pyi +1095 -0
  28. rustegon-0.1.0/src/rustegon/_pb/document_pb2_grpc.py +421 -0
  29. rustegon-0.1.0/src/rustegon/_pb/document_pb2_grpc.pyi +159 -0
  30. rustegon-0.1.0/src/rustegon/_pb/error_pb2.py +40 -0
  31. rustegon-0.1.0/src/rustegon/_pb/error_pb2.pyi +98 -0
  32. rustegon-0.1.0/src/rustegon/_pb/error_pb2_grpc.py +24 -0
  33. rustegon-0.1.0/src/rustegon/_pb/error_pb2_grpc.pyi +22 -0
  34. rustegon-0.1.0/src/rustegon/_pb/query_ast_pb2.py +294 -0
  35. rustegon-0.1.0/src/rustegon/_pb/query_ast_pb2.pyi +4548 -0
  36. rustegon-0.1.0/src/rustegon/_pb/query_ast_pb2_grpc.py +24 -0
  37. rustegon-0.1.0/src/rustegon/_pb/query_ast_pb2_grpc.pyi +22 -0
  38. rustegon-0.1.0/src/rustegon/_pb/query_pb2.py +74 -0
  39. rustegon-0.1.0/src/rustegon/_pb/query_pb2.pyi +544 -0
  40. rustegon-0.1.0/src/rustegon/_pb/query_pb2_grpc.py +251 -0
  41. rustegon-0.1.0/src/rustegon/_pb/query_pb2_grpc.pyi +117 -0
  42. rustegon-0.1.0/src/rustegon/_pb/schema_pb2.py +132 -0
  43. rustegon-0.1.0/src/rustegon/_pb/schema_pb2.pyi +1130 -0
  44. rustegon-0.1.0/src/rustegon/_pb/schema_pb2_grpc.py +726 -0
  45. rustegon-0.1.0/src/rustegon/_pb/schema_pb2_grpc.pyi +240 -0
  46. rustegon-0.1.0/src/rustegon/_pb/session_pb2.py +44 -0
  47. rustegon-0.1.0/src/rustegon/_pb/session_pb2.pyi +110 -0
  48. rustegon-0.1.0/src/rustegon/_pb/session_pb2_grpc.py +146 -0
  49. rustegon-0.1.0/src/rustegon/_pb/session_pb2_grpc.pyi +78 -0
  50. rustegon-0.1.0/src/rustegon/_pb/transaction_pb2.py +60 -0
  51. rustegon-0.1.0/src/rustegon/_pb/transaction_pb2.pyi +300 -0
  52. rustegon-0.1.0/src/rustegon/_pb/transaction_pb2_grpc.py +283 -0
  53. rustegon-0.1.0/src/rustegon/_pb/transaction_pb2_grpc.pyi +117 -0
  54. rustegon-0.1.0/src/rustegon/_scram.py +130 -0
  55. rustegon-0.1.0/src/rustegon/_version.py +5 -0
  56. rustegon-0.1.0/src/rustegon/builders.py +630 -0
  57. rustegon-0.1.0/src/rustegon/client.py +1095 -0
  58. rustegon-0.1.0/src/rustegon/errors.py +208 -0
  59. rustegon-0.1.0/src/rustegon/extjson.py +427 -0
  60. rustegon-0.1.0/src/rustegon/mapping.py +448 -0
  61. rustegon-0.1.0/src/rustegon/py.typed +0 -0
  62. rustegon-0.1.0/src/rustegon/rdoc.py +443 -0
  63. rustegon-0.1.0/src/rustegon/session.py +49 -0
  64. rustegon-0.1.0/src/rustegon/settings.py +368 -0
  65. rustegon-0.1.0/src/rustegon/sync.py +364 -0
  66. rustegon-0.1.0/src/rustegon/types.py +223 -0
@@ -0,0 +1,7 @@
1
+ .venv/
2
+ .mypy_cache/
3
+ .ruff_cache/
4
+ .pytest_cache/
5
+ __pycache__/
6
+ build/
7
+ dist/
@@ -0,0 +1,90 @@
1
+ Metadata-Version: 2.5
2
+ Name: rustegon
3
+ Version: 0.1.0
4
+ Summary: The official Python driver of the Rustegon document database.
5
+ Project-URL: Homepage, https://github.com/pegostar/rustegon/tree/main/drivers/python#readme
6
+ Project-URL: Repository, https://github.com/pegostar/rustegon
7
+ Project-URL: Documentation, https://github.com/pegostar/rustegon/blob/main/docs/specifications/python-driver.md
8
+ Author: The Rustegon Authors
9
+ License-Expression: Apache-2.0
10
+ Keywords: acid,database,driver,grpc,nosql,rustegon
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Framework :: AsyncIO
13
+ Classifier: Programming Language :: Python :: 3 :: Only
14
+ Classifier: Topic :: Database
15
+ Classifier: Typing :: Typed
16
+ Requires-Python: >=3.11
17
+ Requires-Dist: grpcio<2,>=1.85.1
18
+ Requires-Dist: protobuf<8,>=7.36.2
19
+ Requires-Dist: xxhash<5,>=3.4
20
+ Description-Content-Type: text/markdown
21
+
22
+ # Rustegon Python driver
23
+
24
+ The official Python driver of the Rustegon document database: an asyncio API and a blocking
25
+ facade over the same core. Specification: [`docs/specifications/python-driver.md`](../../docs/specifications/python-driver.md).
26
+ Requires Python 3.11 or later (tested on CPython 3.14). Published on PyPI: `pip install rustegon`.
27
+
28
+ ## Quick start
29
+
30
+ ```python
31
+ from rustegon import RustegonClient, Filter, Updates
32
+
33
+ # DEC-014: host, port, user, password, database. A default single node is plain text (ADR-034).
34
+ with RustegonClient("rustegon://app_user:secret@localhost:7700/shop") as client:
35
+ orders = client.get_database().get_collection("orders")
36
+ orders.insert_one({"_id": 1, "status": "paid", "total": 12})
37
+ for order in orders.find(Filter.eq("status", "paid")):
38
+ print(order)
39
+ orders.update_one(Filter.id(1), Updates.set("status", "shipped"))
40
+ ```
41
+
42
+ The same with asyncio:
43
+
44
+ ```python
45
+ import asyncio
46
+ from rustegon import AsyncRustegonClient, ClientSettings, Credential, Filter, Updates
47
+
48
+
49
+ async def main() -> None:
50
+ settings = ClientSettings(
51
+ hosts=[("db1.example.com", 7700)],
52
+ credential=Credential.scram("app_user", "secret"), # or Credential.api_key / Credential.x509
53
+ tls_ca_file="/etc/rustegon/ca.crt", # any TLS option turns TLS on
54
+ database="shop",
55
+ )
56
+ async with AsyncRustegonClient(settings) as client:
57
+ orders = client.get_database().get_collection("orders")
58
+ async for order in orders.find(Filter.gte("total", 10)).limit(20):
59
+ print(order)
60
+
61
+ async def pay(txn) -> None: # re-run on conflicts (transactions.md §5)
62
+ await txn.get_collection("orders").update_one(Filter.id(1), Updates.set("status", "paid"))
63
+
64
+ await client.with_transaction(pay)
65
+
66
+
67
+ asyncio.run(main())
68
+ ```
69
+
70
+ Documents are `dict` (field order = insertion order) or dataclasses
71
+ (`get_collection("orders", Order)`, markers in `rustegon.mapping`). Values: `int` int64, `float`,
72
+ `Decimal` decimal128, timezone-aware `datetime`, `bytes`, `uuid.UUID`, `ObjectId`, `Vector`, …
73
+ (python-driver.md §7). Errors are `rustegon.errors.RustegonException` subclasses with `code`,
74
+ `retryable` and `trace_id`; reads and idempotent writes are retried once by default.
75
+
76
+ ## Development
77
+
78
+ ```bash
79
+ cd drivers/python
80
+ python -m venv .venv && .venv/Scripts/python -m pip install -e . --group dev # .venv/bin on Linux
81
+ .venv/Scripts/python -m ruff check . && .venv/Scripts/python -m ruff format --check .
82
+ .venv/Scripts/python -m mypy # --strict (pyproject)
83
+ RUSTEGON_BIN_DIR=<dir with rustegon and rustegond> .venv/Scripts/python -m pytest
84
+ python scripts/generate.py # regenerate src/rustegon/_pb and _error_table.py (PD-171)
85
+ ```
86
+
87
+ Without `RUSTEGON_BIN_DIR` (default `<repo>/target/debug`) the server tests are skipped (they
88
+ fail under `CI=true`). The conformance runner writes `RUSTEGON_CONFORMANCE_RESULTS` (default
89
+ `build/conformance-results.json`), compared with the .NET and Java results by
90
+ `scripts/ci-local.sh` (AC-DRV-003). Server binaries must follow ADR-034 (plain text by default, `init --tls`).
@@ -0,0 +1,69 @@
1
+ # Rustegon Python driver
2
+
3
+ The official Python driver of the Rustegon document database: an asyncio API and a blocking
4
+ facade over the same core. Specification: [`docs/specifications/python-driver.md`](../../docs/specifications/python-driver.md).
5
+ Requires Python 3.11 or later (tested on CPython 3.14). Published on PyPI: `pip install rustegon`.
6
+
7
+ ## Quick start
8
+
9
+ ```python
10
+ from rustegon import RustegonClient, Filter, Updates
11
+
12
+ # DEC-014: host, port, user, password, database. A default single node is plain text (ADR-034).
13
+ with RustegonClient("rustegon://app_user:secret@localhost:7700/shop") as client:
14
+ orders = client.get_database().get_collection("orders")
15
+ orders.insert_one({"_id": 1, "status": "paid", "total": 12})
16
+ for order in orders.find(Filter.eq("status", "paid")):
17
+ print(order)
18
+ orders.update_one(Filter.id(1), Updates.set("status", "shipped"))
19
+ ```
20
+
21
+ The same with asyncio:
22
+
23
+ ```python
24
+ import asyncio
25
+ from rustegon import AsyncRustegonClient, ClientSettings, Credential, Filter, Updates
26
+
27
+
28
+ async def main() -> None:
29
+ settings = ClientSettings(
30
+ hosts=[("db1.example.com", 7700)],
31
+ credential=Credential.scram("app_user", "secret"), # or Credential.api_key / Credential.x509
32
+ tls_ca_file="/etc/rustegon/ca.crt", # any TLS option turns TLS on
33
+ database="shop",
34
+ )
35
+ async with AsyncRustegonClient(settings) as client:
36
+ orders = client.get_database().get_collection("orders")
37
+ async for order in orders.find(Filter.gte("total", 10)).limit(20):
38
+ print(order)
39
+
40
+ async def pay(txn) -> None: # re-run on conflicts (transactions.md §5)
41
+ await txn.get_collection("orders").update_one(Filter.id(1), Updates.set("status", "paid"))
42
+
43
+ await client.with_transaction(pay)
44
+
45
+
46
+ asyncio.run(main())
47
+ ```
48
+
49
+ Documents are `dict` (field order = insertion order) or dataclasses
50
+ (`get_collection("orders", Order)`, markers in `rustegon.mapping`). Values: `int` int64, `float`,
51
+ `Decimal` decimal128, timezone-aware `datetime`, `bytes`, `uuid.UUID`, `ObjectId`, `Vector`, …
52
+ (python-driver.md §7). Errors are `rustegon.errors.RustegonException` subclasses with `code`,
53
+ `retryable` and `trace_id`; reads and idempotent writes are retried once by default.
54
+
55
+ ## Development
56
+
57
+ ```bash
58
+ cd drivers/python
59
+ python -m venv .venv && .venv/Scripts/python -m pip install -e . --group dev # .venv/bin on Linux
60
+ .venv/Scripts/python -m ruff check . && .venv/Scripts/python -m ruff format --check .
61
+ .venv/Scripts/python -m mypy # --strict (pyproject)
62
+ RUSTEGON_BIN_DIR=<dir with rustegon and rustegond> .venv/Scripts/python -m pytest
63
+ python scripts/generate.py # regenerate src/rustegon/_pb and _error_table.py (PD-171)
64
+ ```
65
+
66
+ Without `RUSTEGON_BIN_DIR` (default `<repo>/target/debug`) the server tests are skipped (they
67
+ fail under `CI=true`). The conformance runner writes `RUSTEGON_CONFORMANCE_RESULTS` (default
68
+ `build/conformance-results.json`), compared with the .NET and Java results by
69
+ `scripts/ci-local.sh` (AC-DRV-003). Server binaries must follow ADR-034 (plain text by default, `init --tls`).
@@ -0,0 +1,101 @@
1
+ # The Rustegon Python driver (python-driver.md, DEC-014, FR-DRV-001/002).
2
+ [build-system]
3
+ requires = ["hatchling==1.33.0"]
4
+ build-backend = "hatchling.build"
5
+
6
+ [project]
7
+ name = "rustegon"
8
+ dynamic = ["version"]
9
+ description = "The official Python driver of the Rustegon document database."
10
+ readme = "README.md"
11
+ license = "Apache-2.0"
12
+ requires-python = ">=3.11"
13
+ authors = [{ name = "The Rustegon Authors" }]
14
+ keywords = ["rustegon", "database", "driver", "nosql", "acid", "grpc"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Framework :: AsyncIO",
18
+ "Programming Language :: Python :: 3 :: Only",
19
+ "Topic :: Database",
20
+ "Typing :: Typed",
21
+ ]
22
+ # Lower bounds: the generated stubs (src/rustegon/_pb, PD-171) check the protobuf and grpcio
23
+ # runtime versions they were generated with. Upper bounds: the next major versions.
24
+ dependencies = [
25
+ "grpcio>=1.85.1,<2",
26
+ "protobuf>=7.36.2,<8",
27
+ "xxhash>=3.4,<5",
28
+ ]
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/pegostar/rustegon/tree/main/drivers/python#readme"
32
+ Repository = "https://github.com/pegostar/rustegon"
33
+ Documentation = "https://github.com/pegostar/rustegon/blob/main/docs/specifications/python-driver.md"
34
+
35
+ # Development tools (PD-175): exact pins; `pip install -e . --group dev` (scripts/ci-local.sh).
36
+ [dependency-groups]
37
+ dev = [
38
+ "grpc-stubs==1.53.0.6",
39
+ "grpcio-tools==1.85.1",
40
+ "mypy==2.4.1",
41
+ "mypy-protobuf==5.1.0",
42
+ "pytest==9.2.0",
43
+ "pytest-asyncio==1.5.0",
44
+ "PyYAML==6.0.3",
45
+ "ruff==0.17.5",
46
+ "types-protobuf==7.35.1.20260906",
47
+ "types-PyYAML==6.0.12.20261113",
48
+ ]
49
+
50
+ [tool.hatch.version]
51
+ path = "src/rustegon/_version.py"
52
+
53
+ [tool.hatch.build.targets.wheel]
54
+ packages = ["src/rustegon"]
55
+
56
+ [tool.hatch.build.targets.sdist]
57
+ include = ["src/rustegon", "README.md", "pyproject.toml"]
58
+
59
+ [tool.pytest.ini_options]
60
+ testpaths = ["tests"]
61
+ pythonpath = ["src", "."]
62
+ asyncio_mode = "auto"
63
+ asyncio_default_fixture_loop_scope = "session"
64
+ asyncio_default_test_loop_scope = "session"
65
+ markers = [
66
+ "server: needs rustegond from RUSTEGON_BIN_DIR (PD-072)",
67
+ "conformance: the shared conformance suite (TC-DRV-CONF-*)",
68
+ ]
69
+
70
+ [tool.mypy]
71
+ strict = true
72
+ python_version = "3.11"
73
+ mypy_path = "src"
74
+ packages = ["rustegon", "tests"]
75
+ exclude = ["src/rustegon/_pb/.*_pb2(_grpc)?\\.py$"]
76
+
77
+ [[tool.mypy.overrides]]
78
+ module = ["rustegon._pb.*"]
79
+ ignore_errors = true
80
+
81
+ [[tool.mypy.overrides]]
82
+ module = ["xxhash"]
83
+ ignore_missing_imports = true
84
+
85
+ [tool.ruff]
86
+ line-length = 120
87
+ target-version = "py311"
88
+ extend-exclude = ["src/rustegon/_pb"]
89
+
90
+ [tool.ruff.lint]
91
+ select = ["E", "F", "W", "I", "B", "UP", "S", "A", "BLE", "SIM", "RUF", "PL", "N"]
92
+ ignore = [
93
+ "N818", # exception names follow the cross-driver names (RustegonException, ...), java-driver.md §11
94
+ "PLR0911", "PLR0912", "PLR0913", "PLR0915", "PLR2004", # protocol code has many branches and literals
95
+ "S101", # assert in tests
96
+ "RUF001", "RUF002", "RUF003", # typographic characters in docs (–, ×, …) are intended
97
+ "PLR0917", # positional arguments mirror the model signatures
98
+ ]
99
+
100
+ [tool.ruff.lint.per-file-ignores]
101
+ "tests/*" = ["S", "PLW0603", "BLE001"]
@@ -0,0 +1,129 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright The Rustegon Authors
3
+ """The official Python driver of the Rustegon document database (python-driver.md).
4
+
5
+ ``AsyncRustegonClient`` is the asyncio API; ``RustegonClient`` the blocking facade over it
6
+ (PD-170). Both take ``ClientSettings`` or a ``rustegon://`` connection string.
7
+ """
8
+
9
+ from rustegon._version import __version__
10
+ from rustegon.builders import BulkOperation, Filter, IndexKey, Projection, Sort, Update, Updates
11
+ from rustegon.client import (
12
+ AsyncCollection,
13
+ AsyncCursor,
14
+ AsyncDatabase,
15
+ AsyncFind,
16
+ AsyncRustegonClient,
17
+ AsyncTransaction,
18
+ BulkWriteError,
19
+ BulkWriteResult,
20
+ DeleteResult,
21
+ IndexInfo,
22
+ IndexState,
23
+ InsertManyResult,
24
+ InsertOneResult,
25
+ IsolationLevel,
26
+ ServerInfo,
27
+ TransactionOptions,
28
+ UpdateResult,
29
+ Validator,
30
+ )
31
+ from rustegon.errors import (
32
+ AuthenticationException,
33
+ AuthorizationException,
34
+ CommitOutcomeUnknownException,
35
+ DocumentValidationException,
36
+ DuplicateKeyException,
37
+ PasswordChangeRequiredException,
38
+ QuerySyntaxException,
39
+ RateLimitedException,
40
+ RDocError,
41
+ RustegonClientException,
42
+ RustegonException,
43
+ RustegonServerException,
44
+ RustegonTimeoutException,
45
+ TransactionAbortedException,
46
+ TransactionConflictException,
47
+ UnavailableException,
48
+ )
49
+ from rustegon.session import ClientSession
50
+ from rustegon.settings import ClientSettings, Credential, ReadConsistency, WriteConcern
51
+ from rustegon.sync import Collection, Cursor, Database, Find, RustegonClient, Transaction
52
+ from rustegon.types import (
53
+ MAX_KEY,
54
+ MIN_KEY,
55
+ Binary,
56
+ Counter,
57
+ DatetimeMs,
58
+ MaxKey,
59
+ MinKey,
60
+ ObjectId,
61
+ Timestamp,
62
+ Vector,
63
+ )
64
+
65
+ __all__ = [
66
+ "MAX_KEY",
67
+ "MIN_KEY",
68
+ "AsyncCollection",
69
+ "AsyncCursor",
70
+ "AsyncDatabase",
71
+ "AsyncFind",
72
+ "AsyncRustegonClient",
73
+ "AsyncTransaction",
74
+ "AuthenticationException",
75
+ "AuthorizationException",
76
+ "Binary",
77
+ "BulkOperation",
78
+ "BulkWriteError",
79
+ "BulkWriteResult",
80
+ "ClientSession",
81
+ "ClientSettings",
82
+ "Collection",
83
+ "CommitOutcomeUnknownException",
84
+ "Counter",
85
+ "Credential",
86
+ "Cursor",
87
+ "Database",
88
+ "DatetimeMs",
89
+ "DeleteResult",
90
+ "DocumentValidationException",
91
+ "DuplicateKeyException",
92
+ "Filter",
93
+ "Find",
94
+ "IndexInfo",
95
+ "IndexKey",
96
+ "IndexState",
97
+ "InsertManyResult",
98
+ "InsertOneResult",
99
+ "IsolationLevel",
100
+ "MaxKey",
101
+ "MinKey",
102
+ "ObjectId",
103
+ "PasswordChangeRequiredException",
104
+ "Projection",
105
+ "QuerySyntaxException",
106
+ "RDocError",
107
+ "RateLimitedException",
108
+ "ReadConsistency",
109
+ "RustegonClient",
110
+ "RustegonClientException",
111
+ "RustegonException",
112
+ "RustegonServerException",
113
+ "RustegonTimeoutException",
114
+ "ServerInfo",
115
+ "Sort",
116
+ "Timestamp",
117
+ "Transaction",
118
+ "TransactionAbortedException",
119
+ "TransactionConflictException",
120
+ "TransactionOptions",
121
+ "UnavailableException",
122
+ "Update",
123
+ "UpdateResult",
124
+ "Updates",
125
+ "Validator",
126
+ "Vector",
127
+ "WriteConcern",
128
+ "__version__",
129
+ ]
@@ -0,0 +1,102 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright The Rustegon Authors
3
+ """IEEE 754-2008 decimal128, binary integer decimal (BID) encoding (data-model.md §2, §4).
4
+
5
+ ``decimal.Decimal`` keeps the cohort (``12.50`` stays ``12.50``) and its ``str`` is IEEE
6
+ "to-scientific-string", so it is the Python type of decimal128; this module converts it to and
7
+ from the 16 bytes (u128 little-endian) of RDoc.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+ from decimal import Decimal
14
+ from typing import Final
15
+
16
+ MAX_COEFFICIENT: Final = 10**34 - 1
17
+ EXP_MIN: Final = -6176
18
+ EXP_MAX: Final = 6111
19
+ _BIAS: Final = 6176
20
+ _SMALL_COEFF_MASK: Final = (1 << 113) - 1
21
+ _NAN: Final = 0x7C << 120
22
+ _INF: Final = 0x78 << 120
23
+ _SIGN: Final = 1 << 127
24
+
25
+ # IEEE 754 decimal character sequence (no whitespace, no underscores: stricter than Decimal()).
26
+ _SYNTAX: Final = re.compile(
27
+ r"[+-]?(?:(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|[Ii][Nn][Ff](?:[Ii][Nn][Ii][Tt][Yy])?|[Nn][Aa][Nn])",
28
+ re.ASCII,
29
+ )
30
+
31
+
32
+ class Decimal128Error(ValueError):
33
+ """A decimal that decimal128 cannot hold exactly."""
34
+
35
+
36
+ def parse(text: str) -> Decimal:
37
+ """The decimal of an IEEE decimal string; refuses what decimal128 cannot hold exactly."""
38
+ if not _SYNTAX.fullmatch(text):
39
+ raise Decimal128Error(f"not a decimal: {text!r}")
40
+ d = Decimal(text)
41
+ encode(d) # range and precision check
42
+ return d
43
+
44
+
45
+ def encode(value: Decimal) -> bytes:
46
+ """The canonical BID bytes of ``value`` (exact: never rounds)."""
47
+ if value.is_nan():
48
+ if value.is_snan():
49
+ raise Decimal128Error("signalling NaN is not a decimal128 value")
50
+ return _NAN.to_bytes(16, "little")
51
+ sign = _SIGN if value.is_signed() else 0
52
+ if value.is_infinite():
53
+ return (sign | _INF).to_bytes(16, "little")
54
+ t = value.as_tuple()
55
+ coefficient = int("".join(map(str, t.digits)) or "0")
56
+ if not isinstance(t.exponent, int): # pragma: no cover - finite values have an int exponent
57
+ raise Decimal128Error("unexpected special value")
58
+ exponent: int = t.exponent
59
+ # Exact only: drop trailing zeros while the coefficient is too long, then bring the
60
+ # exponent into range by adding or removing zeros (IEEE clamping; data-model.md §2 notes).
61
+ while coefficient > MAX_COEFFICIENT and coefficient % 10 == 0:
62
+ coefficient //= 10
63
+ exponent += 1
64
+ if coefficient > MAX_COEFFICIENT:
65
+ raise Decimal128Error("more than 34 significant digits")
66
+ if coefficient == 0:
67
+ exponent = min(max(exponent, EXP_MIN), EXP_MAX)
68
+ while exponent > EXP_MAX:
69
+ coefficient *= 10
70
+ exponent -= 1
71
+ if coefficient > MAX_COEFFICIENT:
72
+ raise Decimal128Error("exponent out of the decimal128 range")
73
+ while exponent < EXP_MIN:
74
+ if coefficient % 10 != 0:
75
+ raise Decimal128Error("exponent out of the decimal128 range")
76
+ coefficient //= 10
77
+ exponent += 1
78
+ bits = sign | ((exponent + _BIAS) << 113) | coefficient
79
+ return bits.to_bytes(16, "little")
80
+
81
+
82
+ def decode(raw: bytes) -> Decimal:
83
+ """The decimal of 16 BID bytes; non-canonical encodings are normalised (IEEE rules)."""
84
+ bits = int.from_bytes(raw, "little")
85
+ negative = bool(bits & _SIGN)
86
+ top5 = (bits >> 122) & 0x1F
87
+ if top5 == 0x1F:
88
+ return Decimal("NaN")
89
+ if top5 == 0x1E:
90
+ return Decimal("-Infinity" if negative else "Infinity")
91
+ if (bits >> 125) & 0x3 == 0x3:
92
+ # Large-coefficient form: the coefficient is >= 2^113 > 10^34 - 1, i.e. non-canonical: 0.
93
+ biased = (bits >> 111) & 0x3FFF
94
+ coefficient = 0
95
+ else:
96
+ biased = (bits >> 113) & 0x3FFF
97
+ coefficient = bits & _SMALL_COEFF_MASK
98
+ if coefficient > MAX_COEFFICIENT:
99
+ coefficient = 0
100
+ exponent = min(biased, EXP_MAX + _BIAS) - _BIAS
101
+ digits = tuple(int(c) for c in str(coefficient))
102
+ return Decimal((1 if negative else 0, digits, exponent))
@@ -0,0 +1,83 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright The Rustegon Authors
3
+
4
+ """Error table generated from drivers/conformance/generated/errors.json - do not edit.
5
+
6
+ Regenerate with ``python scripts/generate.py`` (PD-075, PD-171).
7
+ """
8
+
9
+ from typing import Final
10
+
11
+ # code -> (name, errors-map.yaml class id, gRPC status name, catalog retryable: yes|no|depends)
12
+ CODES: Final[dict[int, tuple[str, str, str, str]]] = {
13
+ 1001: ("InvalidArgument", "Client", "INVALID_ARGUMENT", "no"),
14
+ 1002: ("DocumentTooLarge", "Client", "INVALID_ARGUMENT", "no"),
15
+ 1003: ("NestingTooDeep", "Client", "INVALID_ARGUMENT", "no"),
16
+ 1004: ("InvalidFieldName", "Client", "INVALID_ARGUMENT", "no"),
17
+ 1005: ("DuplicateKey", "DuplicateKey", "ALREADY_EXISTS", "no"),
18
+ 1006: ("SchemaValidationFailed", "DocumentValidation", "INVALID_ARGUMENT", "no"),
19
+ 1007: ("PartitionTooLarge", "Client", "FAILED_PRECONDITION", "no"),
20
+ 1008: ("IndexKeyTooLarge", "Client", "INVALID_ARGUMENT", "no"),
21
+ 1009: ("CounterOverflow", "Client", "OUT_OF_RANGE", "no"),
22
+ 1010: ("QuerySyntaxError", "QuerySyntax", "INVALID_ARGUMENT", "no"),
23
+ 1011: ("QueryTypeError", "QuerySyntax", "INVALID_ARGUMENT", "no"),
24
+ 1012: ("UnknownFunction", "QuerySyntax", "INVALID_ARGUMENT", "no"),
25
+ 1013: ("QueryTooComplex", "Client", "INVALID_ARGUMENT", "no"),
26
+ 1020: ("IndexAlreadyExists", "Client", "ALREADY_EXISTS", "no"),
27
+ 1021: ("IndexNotFound", "Client", "NOT_FOUND", "no"),
28
+ 1022: ("IndexBuildFailed", "Client", "FAILED_PRECONDITION", "no"),
29
+ 1023: ("IndexLimitExceeded", "Client", "RESOURCE_EXHAUSTED", "no"),
30
+ 1024: ("IndexStaleTimeout", "Timeout", "DEADLINE_EXCEEDED", "yes"),
31
+ 1025: ("MultikeyCompoundArrays", "Client", "INVALID_ARGUMENT", "no"),
32
+ 1030: ("NotFound", "Client", "NOT_FOUND", "no"),
33
+ 1031: ("AlreadyExists", "Client", "ALREADY_EXISTS", "no"),
34
+ 1032: ("ResumeTokenExpired", "Client", "OUT_OF_RANGE", "no"),
35
+ 1033: ("SchemaChangeInProgress", "Client", "ABORTED", "yes"),
36
+ 1034: ("DescriptorVersionMismatch", "Server", "ABORTED", "yes"),
37
+ 1040: ("InvalidVector", "Client", "INVALID_ARGUMENT", "no"),
38
+ 1041: ("InvalidGeometry", "Client", "INVALID_ARGUMENT", "no"),
39
+ 2001: ("TransactionConflict", "TransactionConflict", "ABORTED", "yes"),
40
+ 2002: ("TransactionAborted", "TransactionAborted", "ABORTED", "conditional"),
41
+ 2003: ("TransactionTimeout", "Timeout", "DEADLINE_EXCEEDED", "no"),
42
+ 2004: ("TransactionTooLarge", "Client", "RESOURCE_EXHAUSTED", "no"),
43
+ 2005: ("DeadlockDetected", "TransactionConflict", "ABORTED", "yes"),
44
+ 2006: ("CommitOutcomeUnknown", "CommitOutcomeUnknown", "UNKNOWN", "conditional"),
45
+ 2007: ("ReadTimestampTooOld", "TransactionConflict", "ABORTED", "yes"),
46
+ 2008: ("WriteTooOld", "TransactionConflict", "ABORTED", "yes"),
47
+ 2009: ("PreconditionFailed", "Client", "FAILED_PRECONDITION", "no"),
48
+ 3001: ("NotLeaseholder", "Unavailable", "UNAVAILABLE", "yes"),
49
+ 3002: ("Unavailable", "Unavailable", "UNAVAILABLE", "yes"),
50
+ 3003: ("RangeKeyMismatch", "Unavailable", "UNAVAILABLE", "yes"),
51
+ 3004: ("NodeDraining", "Unavailable", "UNAVAILABLE", "yes"),
52
+ 3005: ("ClockOffsetExceeded", "Unavailable", "UNAVAILABLE", "yes"),
53
+ 3006: ("WriteConcernTimeout", "Timeout", "DEADLINE_EXCEEDED", "no"),
54
+ 3007: ("StaleReadUnavailable", "Unavailable", "UNAVAILABLE", "yes"),
55
+ 4001: ("Unauthenticated", "Authentication", "UNAUTHENTICATED", "no"),
56
+ 4002: ("PermissionDenied", "Authorization", "PERMISSION_DENIED", "no"),
57
+ 4003: ("RateLimited", "RateLimited", "RESOURCE_EXHAUSTED", "yes"),
58
+ 4004: ("TlsRequired", "Authentication", "FAILED_PRECONDITION", "no"),
59
+ 4005: ("SessionExpired", "Authentication", "UNAUTHENTICATED", "yes"),
60
+ 4006: ("KeyUnavailable", "Server", "FAILED_PRECONDITION", "no"),
61
+ 4007: ("AccountLocked", "Authentication", "PERMISSION_DENIED", "no"),
62
+ 5001: ("Internal", "Server", "INTERNAL", "no"),
63
+ 5002: ("StorageCorruption", "Server", "DATA_LOSS", "no"),
64
+ 5003: ("DiskFull", "Server", "RESOURCE_EXHAUSTED", "yes"),
65
+ 5004: ("ResourceExhausted", "Server", "RESOURCE_EXHAUSTED", "yes"),
66
+ 5005: ("Cancelled", "Server", "CANCELLED", "no"),
67
+ 5006: ("DeadlineExceeded", "Timeout", "DEADLINE_EXCEEDED", "no"),
68
+ 5007: ("VersionIncompatible", "Client", "FAILED_PRECONDITION", "no"),
69
+ }
70
+
71
+ # gRPC status name -> (class id, synthesized code, retryable) for failures without ErrorDetail
72
+ TRANSPORT: Final[dict[str, tuple[str, int, bool]]] = {
73
+ "UNKNOWN": ("Server", 5001, False),
74
+ "DEADLINE_EXCEEDED": ("Timeout", 5006, False),
75
+ "PERMISSION_DENIED": ("Authorization", 4002, False),
76
+ "RESOURCE_EXHAUSTED": ("Server", 5004, True),
77
+ "INTERNAL": ("Server", 5001, False),
78
+ "UNAVAILABLE": ("Unavailable", 3002, True),
79
+ "UNAUTHENTICATED": ("Authentication", 4001, False),
80
+ "default": ("Server", 5001, False),
81
+ }
82
+
83
+ UNKNOWN: Final = "Base"