dynoxide 1.8.0__py3-none-win_amd64.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.
dynoxide/__init__.py ADDED
@@ -0,0 +1,28 @@
1
+ """Start a Dynoxide server, a DynamoDB-compatible engine, from Python.
2
+
3
+ import boto3
4
+ import dynoxide
5
+
6
+ with dynoxide.start() as server:
7
+ client = boto3.client("dynamodb", **server.client_kwargs())
8
+ client.list_tables()
9
+
10
+ The pytest plugin in ``dynoxide.pytest_plugin`` loads on its own and gives
11
+ tests ``dynoxide``, ``dynamodb_client``, ``dynamodb_resource`` and
12
+ ``dynoxide_clean`` fixtures.
13
+ """
14
+
15
+ from ._binary import binary_path
16
+ from ._errors import DynoxideError, PortInUseError
17
+ from ._server import Server, start
18
+ from ._version import ENGINE_VERSION, __version__
19
+
20
+ __all__ = [
21
+ "ENGINE_VERSION",
22
+ "DynoxideError",
23
+ "PortInUseError",
24
+ "Server",
25
+ "__version__",
26
+ "binary_path",
27
+ "start",
28
+ ]
dynoxide/__main__.py ADDED
@@ -0,0 +1,35 @@
1
+ """The ``dynoxide`` command: runs the binary that came with this package."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import subprocess
7
+ import sys
8
+
9
+ from ._binary import WINDOWS, binary_path
10
+ from ._errors import DynoxideError
11
+
12
+
13
+ def main() -> None:
14
+ try:
15
+ path = binary_path()
16
+ except DynoxideError as err:
17
+ print(f"dynoxide: {err.message}", file=sys.stderr)
18
+ sys.exit(1)
19
+ args = [path, *sys.argv[1:]]
20
+ if not WINDOWS:
21
+ # Replaces this process, so signals and the exit status are the
22
+ # binary's own.
23
+ os.execv(path, args)
24
+ # Windows has no exec that keeps the process, so run it and pass its
25
+ # status on. Ctrl+C reaches the binary too, and it decides what to do.
26
+ process = subprocess.Popen(args)
27
+ while True:
28
+ try:
29
+ sys.exit(process.wait())
30
+ except KeyboardInterrupt:
31
+ continue
32
+
33
+
34
+ if __name__ == "__main__":
35
+ main()
Binary file
dynoxide/_binary.py ADDED
@@ -0,0 +1,245 @@
1
+ """Finding the dynoxide binary, and checking the version of one we didn't ship."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import platform
7
+ import re
8
+ import subprocess
9
+ import sys
10
+ from collections.abc import Mapping, Sequence
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+
14
+ from ._errors import (
15
+ BINARY_MISSING,
16
+ TOO_OLD,
17
+ UNSUPPORTED_PLATFORM,
18
+ VERSION_CHECK_FAILED,
19
+ DynoxideError,
20
+ )
21
+
22
+ WINDOWS = sys.platform == "win32"
23
+ EXE = "dynoxide.exe" if WINDOWS else "dynoxide"
24
+
25
+ # The first release with --ready-json and --exit-with-parent.
26
+ LAUNCHER_FLAGS_SINCE = (1, 7, 0)
27
+ # The oldest that can be started at all: earlier ones print the port asked for
28
+ # rather than the one bound, so --port 0 can't work.
29
+ OLDEST_SUPPORTED = (1, 6, 0)
30
+
31
+ VERSION_TIMEOUT = 10.0
32
+ _VERSION_LINE = re.compile(r"^dynoxide ((\d+)\.(\d+)\.(\d+)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)\s*$")
33
+ # A console script that runs this package is small; the real binary is
34
+ # megabytes. Anything bigger isn't read.
35
+ _SHIM_MAX_BYTES = 1 << 20
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class Binary:
40
+ """A binary to run, where it came from, and how to start it."""
41
+
42
+ path: str
43
+ source: str # "option", "env", "path" or "package"
44
+ version: str | None = None # None for the bundled binary, which isn't asked
45
+ launcher_flags: bool = True
46
+
47
+ def describe(self) -> str:
48
+ found = {
49
+ "option": "the binary argument",
50
+ "env": "DYNOXIDE_BINARY",
51
+ "path": "PATH",
52
+ "package": "this package",
53
+ }[self.source]
54
+ version = f" {self.version}" if self.version else ""
55
+ return f"dynoxide{version} at {self.path}, from {found}"
56
+
57
+
58
+ def binary_path() -> str:
59
+ """The binary that came with this package.
60
+
61
+ Raises DynoxideError with code UNSUPPORTED_PLATFORM when there isn't one:
62
+ pip installed the source distribution because no wheel matched.
63
+ """
64
+ bundled = Path(__file__).resolve().parent / "_bin" / EXE
65
+ if not bundled.is_file():
66
+ raise DynoxideError(
67
+ UNSUPPORTED_PLATFORM,
68
+ f"This install of the dynoxide package has no binary for {_platform_name()}: "
69
+ "pip installed it from source because no wheel matches this platform. "
70
+ "Set DYNOXIDE_BINARY to a dynoxide executable for this platform "
71
+ "(https://github.com/nubo-db/dynoxide/releases), or pass binary= to start().",
72
+ )
73
+ return str(bundled)
74
+
75
+
76
+ def resolve(
77
+ binary: str | os.PathLike[str] | None,
78
+ binary_from_path: bool,
79
+ env: Mapping[str, str],
80
+ ) -> Binary:
81
+ """Finds the binary in the launcher contract's order: the binary argument
82
+ (or PATH, when asked for), then DYNOXIDE_BINARY, then the bundled one. A
83
+ path that was asked for but isn't there is an error, not a reason to try
84
+ the next step."""
85
+ if binary is not None:
86
+ return Binary(_existing(binary, "the binary argument"), "option")
87
+ if binary_from_path:
88
+ return Binary(_on_path(env), "path")
89
+ from_env = env.get("DYNOXIDE_BINARY", "")
90
+ if from_env:
91
+ return Binary(_existing(from_env, "DYNOXIDE_BINARY"), "env")
92
+ return Binary(binary_path(), "package")
93
+
94
+
95
+ def checked(found: Binary, command: Sequence[str] = (), env: Mapping[str, str] | None = None) -> Binary:
96
+ """Asks a binary we didn't ship which version it is, and decides how to
97
+ start it. `command` is a prefix for running it through an interpreter, which
98
+ is how the tests run their fake servers."""
99
+ if found.source == "package":
100
+ return found
101
+ version = _ask_version(found.path, command, env)
102
+ numbers = _numbers(version)
103
+ if numbers < OLDEST_SUPPORTED:
104
+ raise DynoxideError(
105
+ TOO_OLD,
106
+ f"The dynoxide binary at {found.path} is {version}, and this package needs "
107
+ f"{_dotted(OLDEST_SUPPORTED)} or later. Leave the binary unset to use the one this "
108
+ "package installed.",
109
+ )
110
+ return Binary(found.path, found.source, version, numbers >= LAUNCHER_FLAGS_SINCE)
111
+
112
+
113
+ def parse_version(output: str) -> str | None:
114
+ """The version from `dynoxide 1.7.0` or `dynoxide 1.7.0-rc.1`, or None."""
115
+ first = output.lstrip().split("\n", 1)[0] if output.strip() else ""
116
+ match = _VERSION_LINE.match(first)
117
+ return match.group(1) if match else None
118
+
119
+
120
+ def child_env(env: Mapping[str, str]) -> dict[str, str]:
121
+ """The environment without DYNOXIDE_ENCRYPTION_KEY: a test server never
122
+ wants encryption, and a release binary refuses to start with it set.
123
+ Windows names ignore case."""
124
+
125
+ def dropped(name: str) -> bool:
126
+ if WINDOWS:
127
+ return name.upper() == "DYNOXIDE_ENCRYPTION_KEY"
128
+ return name == "DYNOXIDE_ENCRYPTION_KEY"
129
+
130
+ return {name: value for name, value in env.items() if not dropped(name)}
131
+
132
+
133
+ def _existing(file: str | os.PathLike[str], source: str) -> str:
134
+ if not isinstance(file, (str, os.PathLike)):
135
+ raise TypeError(f"{source} must be a path to a dynoxide executable, not {type(file).__name__}.")
136
+ path = Path(file)
137
+ absolute = path.absolute()
138
+ if not absolute.is_file():
139
+ name = os.fspath(file)
140
+ bare = (
141
+ " It takes a path, not a command name to look up on PATH (pass binary_from_path=True for that)."
142
+ if os.sep not in name and "/" not in name
143
+ else ""
144
+ )
145
+ raise DynoxideError(
146
+ BINARY_MISSING,
147
+ f"The dynoxide binary at {absolute}, from {source}, isn't a file.{bare} "
148
+ "Point it at a dynoxide executable, or leave it unset to use the one this package installed.",
149
+ )
150
+ return str(absolute)
151
+
152
+
153
+ def _on_path(env: Mapping[str, str]) -> str:
154
+ """The first dynoxide on PATH that isn't this package's own command, which
155
+ would only start the bundled binary as its child."""
156
+ exts = [""]
157
+ if WINDOWS:
158
+ exts = [e.lower() for e in env.get("PATHEXT", ".EXE").split(os.pathsep) if e]
159
+ for folder in env.get("PATH", "").split(os.pathsep):
160
+ if not folder:
161
+ continue
162
+ for ext in exts:
163
+ candidate = Path(folder) / f"dynoxide{ext}"
164
+ if candidate.is_file() and os.access(candidate, os.X_OK) and not _is_our_shim(candidate):
165
+ return str(candidate.absolute())
166
+ raise DynoxideError(
167
+ BINARY_MISSING,
168
+ "binary_from_path=True, but there's no dynoxide executable on PATH other than this "
169
+ "package's own command. Install Dynoxide (for example with Homebrew), or leave "
170
+ "binary_from_path unset to use the binary this package installed.",
171
+ )
172
+
173
+
174
+ def _is_our_shim(candidate: Path) -> bool:
175
+ try:
176
+ if candidate.stat().st_size > _SHIM_MAX_BYTES:
177
+ return False
178
+ return b"dynoxide.__main__" in candidate.read_bytes()
179
+ except OSError:
180
+ return False
181
+
182
+
183
+ def _ask_version(path: str, command: Sequence[str], env: Mapping[str, str] | None) -> str:
184
+ base = dict(os.environ) if env is None else dict(env)
185
+ try:
186
+ result = subprocess.run(
187
+ [*command, path, "--version"],
188
+ stdin=subprocess.DEVNULL,
189
+ capture_output=True,
190
+ env=child_env(base),
191
+ timeout=VERSION_TIMEOUT,
192
+ creationflags=_no_window(),
193
+ )
194
+ except subprocess.TimeoutExpired:
195
+ raise DynoxideError(
196
+ VERSION_CHECK_FAILED,
197
+ f"{path} --version didn't finish within {VERSION_TIMEOUT:g} seconds. Is it a Dynoxide binary?",
198
+ ) from None
199
+ except OSError as err:
200
+ raise DynoxideError(VERSION_CHECK_FAILED, f"Couldn't run {path}: {err}.") from None
201
+
202
+ stdout = result.stdout.decode("utf-8", "replace")
203
+ stderr = result.stderr.decode("utf-8", "replace").strip()
204
+ if result.returncode != 0:
205
+ how = (
206
+ f"was killed by signal {-result.returncode}"
207
+ if result.returncode < 0
208
+ else f"failed with exit status {result.returncode}"
209
+ )
210
+ if result.returncode in (126, 127):
211
+ how += ", which usually means it couldn't be executed at all"
212
+ said = f" It said: {_shown(stderr)}" if stderr else ""
213
+ raise DynoxideError(VERSION_CHECK_FAILED, f"{path} --version {how}.{said}")
214
+ version = parse_version(stdout)
215
+ if version is None:
216
+ raise DynoxideError(
217
+ VERSION_CHECK_FAILED,
218
+ f'{path} --version printed {_shown(stdout)}, not "dynoxide <version>". Is it a Dynoxide binary?',
219
+ )
220
+ return version
221
+
222
+
223
+ def _numbers(version: str) -> tuple[int, int, int]:
224
+ """X.Y.Z only, so a pre-release counts as its release."""
225
+ major, minor, patch = re.split(r"[-+]", version, maxsplit=1)[0].split(".")
226
+ return int(major), int(minor), int(patch)
227
+
228
+
229
+ def _dotted(version: tuple[int, int, int]) -> str:
230
+ return ".".join(str(part) for part in version)
231
+
232
+
233
+ def _shown(text: str) -> str:
234
+ text = re.sub(r"[^\x20-\x7e]+", " ", text.strip())
235
+ if not text:
236
+ return "nothing"
237
+ return '"' + (text[:200] + "..." if len(text) > 200 else text) + '"'
238
+
239
+
240
+ def _platform_name() -> str:
241
+ return f"{platform.system() or sys.platform} {platform.machine() or 'unknown'}"
242
+
243
+
244
+ def _no_window() -> int:
245
+ return getattr(subprocess, "CREATE_NO_WINDOW", 0) if WINDOWS else 0
dynoxide/_env.py ADDED
@@ -0,0 +1,46 @@
1
+ """The environment variables that point AWS SDKs at a Dynoxide server."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from collections.abc import MutableMapping
7
+
8
+ REGION = "us-east-1"
9
+ ACCESS_KEY_ID = "dynoxide"
10
+ SECRET_ACCESS_KEY = "dynoxide"
11
+
12
+ # Names export() sets or removes, so a caller can save and restore them.
13
+ NAMES = (
14
+ "AWS_ENDPOINT_URL_DYNAMODB",
15
+ "AWS_ACCESS_KEY_ID",
16
+ "AWS_SECRET_ACCESS_KEY",
17
+ "AWS_REGION",
18
+ "AWS_DEFAULT_REGION",
19
+ "AWS_IGNORE_CONFIGURED_ENDPOINT_URLS",
20
+ "AWS_SESSION_TOKEN",
21
+ )
22
+
23
+
24
+ def environment(endpoint: str) -> dict[str, str]:
25
+ """The variables for an endpoint. AWS_ENDPOINT_URL is never among them:
26
+ it would send every AWS service to Dynoxide."""
27
+ return {
28
+ "AWS_ENDPOINT_URL_DYNAMODB": endpoint,
29
+ "AWS_ACCESS_KEY_ID": ACCESS_KEY_ID,
30
+ "AWS_SECRET_ACCESS_KEY": SECRET_ACCESS_KEY,
31
+ "AWS_REGION": REGION,
32
+ "AWS_DEFAULT_REGION": REGION,
33
+ # Set to true, here or as ignore_configured_endpoint_urls in the shared
34
+ # config file, this makes botocore ignore AWS_ENDPOINT_URL_DYNAMODB and
35
+ # call AWS. The environment wins over the config file, so false
36
+ # overrides both.
37
+ "AWS_IGNORE_CONFIGURED_ENDPOINT_URLS": "false",
38
+ }
39
+
40
+
41
+ def export(endpoint: str, environ: MutableMapping[str, str] | None = None) -> None:
42
+ """Sets the variables, and removes AWS_SESSION_TOKEN so a real session
43
+ token isn't sent along with the dummy credentials."""
44
+ target = os.environ if environ is None else environ
45
+ target.update(environment(endpoint))
46
+ target.pop("AWS_SESSION_TOKEN", None)
dynoxide/_errors.py ADDED
@@ -0,0 +1,41 @@
1
+ """The errors start() raises."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable
6
+
7
+ # Error codes, the same as the npm package's without its DYNOXIDE_ prefix.
8
+ BINARY_MISSING = "BINARY_MISSING"
9
+ UNSUPPORTED_PLATFORM = "UNSUPPORTED_PLATFORM"
10
+ TOO_OLD = "TOO_OLD"
11
+ VERSION_CHECK_FAILED = "VERSION_CHECK_FAILED"
12
+ SPAWN_FAILED = "SPAWN_FAILED"
13
+ EXITED = "EXITED"
14
+ PORT_IN_USE = "PORT_IN_USE"
15
+ BAD_READY_LINE = "BAD_READY_LINE"
16
+ PORT_ZERO = "PORT_ZERO"
17
+ TIMEOUT = "TIMEOUT"
18
+
19
+
20
+ class DynoxideError(Exception):
21
+ """Dynoxide couldn't be found or started.
22
+
23
+ ``code`` says which of the failures it was, and ``stderr_tail`` holds the
24
+ server's last lines of stderr when there were any.
25
+ """
26
+
27
+ def __init__(self, code: str, message: str, stderr_tail: Iterable[str] = ()) -> None:
28
+ self.code = code
29
+ self.message = message
30
+ self.stderr_tail = list(stderr_tail)
31
+ if self.stderr_tail:
32
+ message += "\n\nLast lines of stderr:\n" + "\n".join(self.stderr_tail)
33
+ super().__init__(message)
34
+
35
+
36
+ class PortInUseError(DynoxideError):
37
+ """The fixed port start() was given is already taken."""
38
+
39
+ def __init__(self, port: int, message: str, stderr_tail: Iterable[str] = ()) -> None:
40
+ self.port = port
41
+ super().__init__(PORT_IN_USE, message, stderr_tail)