litebackup 1.1.0__py3-none-macosx_13_0_arm64.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.
- litebackup/__init__.py +94 -0
- litebackup/_async_transport.py +128 -0
- litebackup/_bin/litebackup +4 -0
- litebackup/_binary.py +111 -0
- litebackup/_credential.py +53 -0
- litebackup/_decode.py +75 -0
- litebackup/_failover.py +476 -0
- litebackup/_foreground.py +266 -0
- litebackup/_generated/__init__.py +1 -0
- litebackup/_generated/error_codes.py +34 -0
- litebackup/_generated/models.py +639 -0
- litebackup/_launch.py +121 -0
- litebackup/_paths.py +82 -0
- litebackup/_pool.py +1142 -0
- litebackup/_transport.py +201 -0
- litebackup/_umask.py +55 -0
- litebackup/_version.py +7 -0
- litebackup/_wire.py +456 -0
- litebackup/client.py +958 -0
- litebackup/errors.py +118 -0
- litebackup/integrations/__init__.py +8 -0
- litebackup/integrations/_sqlite_uri.py +67 -0
- litebackup/integrations/aiosqlite.py +46 -0
- litebackup/integrations/django/__init__.py +19 -0
- litebackup/integrations/django/apps.py +80 -0
- litebackup/integrations/fastapi.py +78 -0
- litebackup/integrations/sqlalchemy.py +159 -0
- litebackup/integrations/sqlite3.py +57 -0
- litebackup/py.typed +0 -0
- litebackup/release.py +122 -0
- litebackup-1.1.0.dist-info/METADATA +174 -0
- litebackup-1.1.0.dist-info/RECORD +34 -0
- litebackup-1.1.0.dist-info/WHEEL +4 -0
- litebackup-1.1.0.dist-info/licenses/LICENSE +21 -0
litebackup/__init__.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Back up, replicate, and restore SQLite databases with Litebackup.
|
|
2
|
+
|
|
3
|
+
The client talks to the litebackup daemon of a session over its unix socket and
|
|
4
|
+
starts it when it is not running, with the credential in LITEBACKUP_API_KEY::
|
|
5
|
+
|
|
6
|
+
from litebackup import Litebackup
|
|
7
|
+
|
|
8
|
+
with Litebackup() as litebackup:
|
|
9
|
+
litebackup.backups.start("/var/lib/app/main.sqlite")
|
|
10
|
+
|
|
11
|
+
AsyncLitebackup has the same groups for asyncio. Driver and framework support is
|
|
12
|
+
in litebackup.integrations: sqlite3, aiosqlite, sqlalchemy, django, and fastapi.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from ._binary import BINARY_PATH_ENVIRONMENT, install_command, litebackup_binary
|
|
16
|
+
from ._credential import API_KEY_ENVIRONMENT
|
|
17
|
+
from ._failover import AsyncFailover, Failover
|
|
18
|
+
from ._generated.models import (
|
|
19
|
+
AcquireResult,
|
|
20
|
+
ArchivedVersion,
|
|
21
|
+
BackupRule,
|
|
22
|
+
DatabaseStatus,
|
|
23
|
+
DatabaseStatusList,
|
|
24
|
+
DrainFailure,
|
|
25
|
+
Event,
|
|
26
|
+
EventList,
|
|
27
|
+
PrefixReplica,
|
|
28
|
+
ReleaseResult,
|
|
29
|
+
ReplicaList,
|
|
30
|
+
RestorableVersion,
|
|
31
|
+
RestoreResult,
|
|
32
|
+
RevertResult,
|
|
33
|
+
ShutdownResult,
|
|
34
|
+
Status,
|
|
35
|
+
StopBackupResult,
|
|
36
|
+
SyncedState,
|
|
37
|
+
VersionList,
|
|
38
|
+
Writer,
|
|
39
|
+
)
|
|
40
|
+
from ._paths import SYSTEM_CONFIGURATION_PATH, session_socket
|
|
41
|
+
from ._pool import DEFAULT_CLEANUP_TIMEOUT, Adapter, AsyncAdapter, AsyncPool, Pool
|
|
42
|
+
from ._version import MINIMUM_DAEMON_VERSION, SDK_VERSION
|
|
43
|
+
from ._wire import Durability, Duration, PathSource, WriteProtection
|
|
44
|
+
from .client import AsyncLitebackup, Litebackup
|
|
45
|
+
from .errors import ErrorCode, LeaseCleanupError, LitebackupError
|
|
46
|
+
|
|
47
|
+
__version__ = SDK_VERSION
|
|
48
|
+
|
|
49
|
+
__all__ = [
|
|
50
|
+
"API_KEY_ENVIRONMENT",
|
|
51
|
+
"BINARY_PATH_ENVIRONMENT",
|
|
52
|
+
"DEFAULT_CLEANUP_TIMEOUT",
|
|
53
|
+
"MINIMUM_DAEMON_VERSION",
|
|
54
|
+
"SDK_VERSION",
|
|
55
|
+
"SYSTEM_CONFIGURATION_PATH",
|
|
56
|
+
"AcquireResult",
|
|
57
|
+
"Adapter",
|
|
58
|
+
"ArchivedVersion",
|
|
59
|
+
"AsyncAdapter",
|
|
60
|
+
"AsyncFailover",
|
|
61
|
+
"AsyncLitebackup",
|
|
62
|
+
"AsyncPool",
|
|
63
|
+
"BackupRule",
|
|
64
|
+
"DatabaseStatus",
|
|
65
|
+
"DatabaseStatusList",
|
|
66
|
+
"DrainFailure",
|
|
67
|
+
"Durability",
|
|
68
|
+
"Duration",
|
|
69
|
+
"ErrorCode",
|
|
70
|
+
"Event",
|
|
71
|
+
"EventList",
|
|
72
|
+
"Failover",
|
|
73
|
+
"LeaseCleanupError",
|
|
74
|
+
"Litebackup",
|
|
75
|
+
"LitebackupError",
|
|
76
|
+
"PathSource",
|
|
77
|
+
"Pool",
|
|
78
|
+
"PrefixReplica",
|
|
79
|
+
"ReleaseResult",
|
|
80
|
+
"ReplicaList",
|
|
81
|
+
"RestorableVersion",
|
|
82
|
+
"RestoreResult",
|
|
83
|
+
"RevertResult",
|
|
84
|
+
"ShutdownResult",
|
|
85
|
+
"Status",
|
|
86
|
+
"StopBackupResult",
|
|
87
|
+
"SyncedState",
|
|
88
|
+
"VersionList",
|
|
89
|
+
"WriteProtection",
|
|
90
|
+
"Writer",
|
|
91
|
+
"install_command",
|
|
92
|
+
"litebackup_binary",
|
|
93
|
+
"session_socket",
|
|
94
|
+
]
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""HTTP/1.1 over the daemon's unix socket with h11 and asyncio streams.
|
|
2
|
+
|
|
3
|
+
Cancelling the task that awaits a call closes its connection, so a cancelled
|
|
4
|
+
call never leaves a half-read answer in the pool.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
import contextlib
|
|
11
|
+
|
|
12
|
+
import h11
|
|
13
|
+
|
|
14
|
+
from ._transport import POOL_SIZE, READ_SIZE, Answer, AnswerReader, request_events
|
|
15
|
+
from .errors import ErrorCode, LitebackupError
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class _AsyncConnection:
|
|
19
|
+
__slots__ = ("protocol", "reader", "writer")
|
|
20
|
+
|
|
21
|
+
def __init__(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
|
|
22
|
+
self.reader = reader
|
|
23
|
+
self.writer = writer
|
|
24
|
+
self.protocol = h11.Connection(our_role=h11.CLIENT)
|
|
25
|
+
|
|
26
|
+
def dropped(self) -> bool:
|
|
27
|
+
return self.reader.at_eof() or self.writer.is_closing()
|
|
28
|
+
|
|
29
|
+
def close(self) -> None:
|
|
30
|
+
self.writer.close()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class AsyncTransport:
|
|
34
|
+
"""Sends requests over a unix socket from one event loop."""
|
|
35
|
+
|
|
36
|
+
def __init__(self, socket_path: str) -> None:
|
|
37
|
+
self.socket_path = socket_path
|
|
38
|
+
self._idle: list[_AsyncConnection] = []
|
|
39
|
+
self._active: set[_AsyncConnection] = set()
|
|
40
|
+
self.closed = False
|
|
41
|
+
|
|
42
|
+
async def _pooled_connection(self) -> tuple[_AsyncConnection, bool]:
|
|
43
|
+
if self.closed:
|
|
44
|
+
raise LitebackupError(ErrorCode.CLOSED, "the client is closed")
|
|
45
|
+
while self._idle:
|
|
46
|
+
connection = self._idle.pop()
|
|
47
|
+
if connection.dropped():
|
|
48
|
+
connection.close()
|
|
49
|
+
continue
|
|
50
|
+
self._active.add(connection)
|
|
51
|
+
return connection, True
|
|
52
|
+
reader, writer = await asyncio.open_unix_connection(self.socket_path)
|
|
53
|
+
if self.closed:
|
|
54
|
+
writer.close()
|
|
55
|
+
raise LitebackupError(ErrorCode.CLOSED, "the client is closed")
|
|
56
|
+
connection = _AsyncConnection(reader, writer)
|
|
57
|
+
self._active.add(connection)
|
|
58
|
+
return connection, False
|
|
59
|
+
|
|
60
|
+
def _return_connection(self, connection: _AsyncConnection, reusable: bool) -> None:
|
|
61
|
+
self._active.discard(connection)
|
|
62
|
+
if reusable and not self.closed and len(self._idle) < POOL_SIZE:
|
|
63
|
+
connection.protocol.start_next_cycle()
|
|
64
|
+
self._idle.append(connection)
|
|
65
|
+
return
|
|
66
|
+
connection.close()
|
|
67
|
+
|
|
68
|
+
async def request(self, method: str, target: str, body: bytes | None, deadline_seconds: float | None) -> Answer:
|
|
69
|
+
"""Sends one request and reads its whole answer; see SyncTransport.request."""
|
|
70
|
+
loop = asyncio.get_running_loop()
|
|
71
|
+
deadline = None if deadline_seconds is None else loop.time() + deadline_seconds
|
|
72
|
+
while True:
|
|
73
|
+
reader = AnswerReader()
|
|
74
|
+
connection: _AsyncConnection | None = None
|
|
75
|
+
reused = False
|
|
76
|
+
try:
|
|
77
|
+
async with asyncio.timeout_at(deadline):
|
|
78
|
+
connection, reused = await self._pooled_connection()
|
|
79
|
+
answer = await self._exchange(connection, method, target, body, reader)
|
|
80
|
+
except asyncio.CancelledError:
|
|
81
|
+
if connection is not None:
|
|
82
|
+
self._return_connection(connection, False)
|
|
83
|
+
raise
|
|
84
|
+
except LitebackupError:
|
|
85
|
+
if connection is not None:
|
|
86
|
+
self._return_connection(connection, False)
|
|
87
|
+
raise
|
|
88
|
+
except TimeoutError as error:
|
|
89
|
+
if connection is not None:
|
|
90
|
+
self._return_connection(connection, False)
|
|
91
|
+
raise LitebackupError(
|
|
92
|
+
ErrorCode.TIMEOUT, "the daemon did not answer within the call's timeout; it may still finish the operation"
|
|
93
|
+
) from error
|
|
94
|
+
except (OSError, h11.ProtocolError, asyncio.IncompleteReadError) as error:
|
|
95
|
+
if connection is not None:
|
|
96
|
+
self._return_connection(connection, False)
|
|
97
|
+
if self.closed:
|
|
98
|
+
raise LitebackupError(ErrorCode.CLOSED, "the client is closed") from error
|
|
99
|
+
if reused and method == "GET" and not reader.started:
|
|
100
|
+
continue
|
|
101
|
+
raise LitebackupError(ErrorCode.CONNECTION_FAILED, str(error) or type(error).__name__) from error
|
|
102
|
+
protocol = connection.protocol
|
|
103
|
+
self._return_connection(connection, protocol.our_state is h11.DONE and protocol.their_state is h11.DONE)
|
|
104
|
+
return answer
|
|
105
|
+
|
|
106
|
+
@staticmethod
|
|
107
|
+
async def _exchange(connection: _AsyncConnection, method: str, target: str, body: bytes | None, reader: AnswerReader) -> Answer:
|
|
108
|
+
data = b"".join(connection.protocol.send(event) or b"" for event in request_events(method, target, body))
|
|
109
|
+
connection.writer.write(data)
|
|
110
|
+
await connection.writer.drain()
|
|
111
|
+
while True:
|
|
112
|
+
event = connection.protocol.next_event()
|
|
113
|
+
if event is h11.NEED_DATA:
|
|
114
|
+
connection.protocol.receive_data(await connection.reader.read(READ_SIZE))
|
|
115
|
+
continue
|
|
116
|
+
if reader.accept(event):
|
|
117
|
+
return reader.answer()
|
|
118
|
+
|
|
119
|
+
async def close(self) -> None:
|
|
120
|
+
"""Closes every connection; calls in flight fail with closed."""
|
|
121
|
+
self.closed = True
|
|
122
|
+
connections = [*self._idle, *self._active]
|
|
123
|
+
self._idle = []
|
|
124
|
+
for connection in connections:
|
|
125
|
+
connection.close()
|
|
126
|
+
for connection in connections:
|
|
127
|
+
with contextlib.suppress(Exception):
|
|
128
|
+
await connection.writer.wait_closed()
|
litebackup/_binary.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Finding the litebackup binary. Nothing is downloaded at runtime."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import shutil
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from importlib import resources
|
|
9
|
+
|
|
10
|
+
from .errors import ErrorCode, LitebackupError
|
|
11
|
+
|
|
12
|
+
BINARY_PATH_ENVIRONMENT = "LITEBACKUP_PATH"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def install_command() -> str:
|
|
16
|
+
"""The one line that installs the litebackup command on Linux and macOS for whoever runs it."""
|
|
17
|
+
return "curl -fsSL https://litebackup.com/cli.sh | bash"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _executable(path: str) -> bool:
|
|
21
|
+
return os.path.isfile(path) and os.access(path, os.X_OK)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def bundled_binary() -> str | None:
|
|
25
|
+
"""The binary this platform's wheel carries, or None for the sdist and pure installs."""
|
|
26
|
+
try:
|
|
27
|
+
candidate = resources.files("litebackup").joinpath("_bin", "litebackup")
|
|
28
|
+
except (ModuleNotFoundError, NotADirectoryError):
|
|
29
|
+
return None
|
|
30
|
+
path = os.fspath(candidate) # type: ignore[call-overload]
|
|
31
|
+
return path if _executable(path) else None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def litebackup_binary(environment: Mapping[str, str] | None = None, binary_path: str | None = None) -> str:
|
|
35
|
+
"""Finds the litebackup binary.
|
|
36
|
+
|
|
37
|
+
The explicit path, then LITEBACKUP_PATH, then the binary the wheel bundles,
|
|
38
|
+
then litebackup on PATH, then ~/.local/bin/litebackup. Raises
|
|
39
|
+
binary_not_found with the install command when there is none, or when the
|
|
40
|
+
explicit path or LITEBACKUP_PATH names no file.
|
|
41
|
+
"""
|
|
42
|
+
environment = os.environ if environment is None else environment
|
|
43
|
+
override = (binary_path or "").strip() or environment.get(BINARY_PATH_ENVIRONMENT, "").strip()
|
|
44
|
+
if override:
|
|
45
|
+
# An explicit path that names no file never falls back to another
|
|
46
|
+
# binary; a file that cannot run fails later, as launch_failed.
|
|
47
|
+
if missing_path(override):
|
|
48
|
+
raise LitebackupError(
|
|
49
|
+
ErrorCode.BINARY_NOT_FOUND,
|
|
50
|
+
f"the litebackup binary {override} does not exist; "
|
|
51
|
+
f"set binary_path or {BINARY_PATH_ENVIRONMENT} to it, or install it with: {install_command()}",
|
|
52
|
+
)
|
|
53
|
+
return override
|
|
54
|
+
bundled = bundled_binary()
|
|
55
|
+
if bundled:
|
|
56
|
+
return bundled
|
|
57
|
+
found = shutil.which("litebackup", path=environment.get("PATH", os.defpath))
|
|
58
|
+
if found:
|
|
59
|
+
return found
|
|
60
|
+
home = environment.get("HOME") or os.path.expanduser("~")
|
|
61
|
+
local = os.path.join(home, ".local", "bin", "litebackup")
|
|
62
|
+
if _executable(local):
|
|
63
|
+
return local
|
|
64
|
+
raise LitebackupError(
|
|
65
|
+
ErrorCode.BINARY_NOT_FOUND,
|
|
66
|
+
f"the litebackup command is not installed; set {BINARY_PATH_ENVIRONMENT} or install it with: {install_command()}",
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def missing_path(path: str) -> bool:
|
|
71
|
+
"""Whether nothing is at path: it, or a directory on its way, does not exist.
|
|
72
|
+
|
|
73
|
+
A path behind a directory this user may not enter is not missing.
|
|
74
|
+
"""
|
|
75
|
+
try:
|
|
76
|
+
os.stat(path)
|
|
77
|
+
except (FileNotFoundError, NotADirectoryError):
|
|
78
|
+
return True
|
|
79
|
+
except OSError:
|
|
80
|
+
return False
|
|
81
|
+
return False
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def start_failure_message(binary: str, error: OSError) -> str:
|
|
85
|
+
"""Why starting binary failed.
|
|
86
|
+
|
|
87
|
+
A file that is there but fails to start as missing cannot run: the
|
|
88
|
+
interpreter its #! line names, or its dynamic loader, is not on this
|
|
89
|
+
machine. The message names that line rather than repeating the file's
|
|
90
|
+
path as if it were missing.
|
|
91
|
+
"""
|
|
92
|
+
if not isinstance(error, (FileNotFoundError, NotADirectoryError)) or missing_path(binary):
|
|
93
|
+
return f"starting {binary} failed: {error}"
|
|
94
|
+
interpreter_line = script_interpreter_line(binary)
|
|
95
|
+
unusable_binary = f"starting {binary} failed: it cannot run because"
|
|
96
|
+
if not interpreter_line:
|
|
97
|
+
return f"{unusable_binary} its interpreter or dynamic loader is not on this machine"
|
|
98
|
+
return f"{unusable_binary} the interpreter its first line names is not on this machine: {interpreter_line}"
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def script_interpreter_line(path: str) -> str:
|
|
102
|
+
"""The #! line that starts the file at path, or "" when it starts with none or cannot be read."""
|
|
103
|
+
try:
|
|
104
|
+
with open(path, "rb") as script:
|
|
105
|
+
start = script.read(256)
|
|
106
|
+
except OSError:
|
|
107
|
+
return ""
|
|
108
|
+
first_line = start.split(b"\n", 1)[0].decode("utf-8", "replace")
|
|
109
|
+
if not first_line.startswith("#!"):
|
|
110
|
+
return ""
|
|
111
|
+
return first_line.strip()
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Telling an API key from a join token, as the daemon does."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from typing import Literal
|
|
7
|
+
|
|
8
|
+
from .errors import invalid_argument
|
|
9
|
+
|
|
10
|
+
API_KEY_ENVIRONMENT = "LITEBACKUP_API_KEY"
|
|
11
|
+
"""Holds the credential a daemon uses when it starts: an API key, or a join token the daemon
|
|
12
|
+
exchanges once for a key of the machine, then @ and the server's address."""
|
|
13
|
+
|
|
14
|
+
# Join and invite tokens start with longer prefixes of an API key's.
|
|
15
|
+
_API_KEY_PREFIX = "litebackup_"
|
|
16
|
+
_JOIN_TOKEN_PREFIX = "litebackup_join_"
|
|
17
|
+
_INVITE_PREFIX = "litebackup_invite_"
|
|
18
|
+
|
|
19
|
+
CredentialType = Literal["api_key", "join_token"]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
# The server address a credential may name, as the daemon checks it: an optional http:// or https://
|
|
23
|
+
# in any case, a host name or a bracketed IPv6 address, an optional port, and an optional path
|
|
24
|
+
# without a query or fragment, of ASCII URL characters and percent escapes.
|
|
25
|
+
_SERVER_ADDRESS = re.compile(
|
|
26
|
+
r"(?:[Hh][Tt][Tt][Pp][Ss]?://)?(?:[A-Za-z0-9._-]+|\[[0-9A-Fa-f:.]+\])(?::[0-9]{1,5})?(?:/(?:[A-Za-z0-9._~!$&'()*+,;=:/-]|%[0-9A-Fa-f]{2})*)?"
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def credential_type(key_and_server: str | None) -> CredentialType | None:
|
|
31
|
+
"""Tells an API key from a join token by prefix; None for an empty credential, which leaves the daemon its saved key.
|
|
32
|
+
|
|
33
|
+
Raises invalid_argument, without repeating the credential, for an invite token, a credential with
|
|
34
|
+
neither prefix, or one without @ and the server's address: a host, or an http:// or https:// URL of one.
|
|
35
|
+
"""
|
|
36
|
+
stripped = (key_and_server or "").strip()
|
|
37
|
+
if not stripped:
|
|
38
|
+
return None
|
|
39
|
+
secret, separator, server = stripped.rpartition("@")
|
|
40
|
+
if not separator or not secret or not _SERVER_ADDRESS.fullmatch(server):
|
|
41
|
+
raise invalid_argument(
|
|
42
|
+
"expected <API_KEY>@<HOST>: an API key or a join token from Machines → Add machine, "
|
|
43
|
+
"then @ and the server's address: a host, or an http:// or https:// URL of one"
|
|
44
|
+
)
|
|
45
|
+
if secret.startswith(_INVITE_PREFIX):
|
|
46
|
+
raise invalid_argument(
|
|
47
|
+
"this is an invite token, which signs a person in to the console; use an API key or a join token from Machines → Add machine"
|
|
48
|
+
)
|
|
49
|
+
if secret.startswith(_JOIN_TOKEN_PREFIX):
|
|
50
|
+
return "join_token"
|
|
51
|
+
if secret.startswith(_API_KEY_PREFIX):
|
|
52
|
+
return "api_key"
|
|
53
|
+
raise invalid_argument(f"expected an API key or a join token, which start with {_API_KEY_PREFIX}; get one from Machines → Add machine")
|
litebackup/_decode.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Decoding JSON answers into the generated dataclasses.
|
|
2
|
+
|
|
3
|
+
Unknown fields are ignored and missing ones take their type's zero value, so a
|
|
4
|
+
newer daemon's answers keep decoding. Literal fields keep values this SDK does
|
|
5
|
+
not know.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import dataclasses
|
|
11
|
+
import types
|
|
12
|
+
import typing
|
|
13
|
+
from datetime import datetime
|
|
14
|
+
from typing import Any, TypeVar
|
|
15
|
+
|
|
16
|
+
Model = TypeVar("Model")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
_field_type_cache: dict[type[Any], dict[str, Any]] = {}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _field_types(cls: type[Any]) -> dict[str, Any]:
|
|
23
|
+
hints = _field_type_cache.get(cls)
|
|
24
|
+
if hints is None:
|
|
25
|
+
hints = _field_type_cache[cls] = typing.get_type_hints(cls)
|
|
26
|
+
return hints
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _zero(annotation: Any) -> Any:
|
|
30
|
+
origin = typing.get_origin(annotation)
|
|
31
|
+
if origin in (types.UnionType, typing.Union):
|
|
32
|
+
return None
|
|
33
|
+
if origin is list or annotation is list:
|
|
34
|
+
return []
|
|
35
|
+
if origin is dict or annotation is dict:
|
|
36
|
+
return {}
|
|
37
|
+
if origin is typing.Literal:
|
|
38
|
+
return ""
|
|
39
|
+
if dataclasses.is_dataclass(annotation) and isinstance(annotation, type):
|
|
40
|
+
return decode(annotation, {})
|
|
41
|
+
return {str: "", int: 0, float: 0.0, bool: False}.get(annotation)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _value(annotation: Any, value: Any) -> Any:
|
|
45
|
+
if value is None:
|
|
46
|
+
return None
|
|
47
|
+
origin = typing.get_origin(annotation)
|
|
48
|
+
if origin in (types.UnionType, typing.Union):
|
|
49
|
+
candidates = [argument for argument in typing.get_args(annotation) if argument is not type(None)]
|
|
50
|
+
return _value(candidates[0], value) if len(candidates) == 1 else value
|
|
51
|
+
if origin is list:
|
|
52
|
+
(item,) = typing.get_args(annotation)
|
|
53
|
+
return [_value(item, element) for element in value]
|
|
54
|
+
if dataclasses.is_dataclass(annotation) and isinstance(annotation, type):
|
|
55
|
+
return decode(annotation, value)
|
|
56
|
+
if annotation is datetime and isinstance(value, str):
|
|
57
|
+
return datetime.fromisoformat(value)
|
|
58
|
+
if annotation is float and isinstance(value, int):
|
|
59
|
+
return float(value)
|
|
60
|
+
return value
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def decode(cls: type[Model], value: Any) -> Model:
|
|
64
|
+
"""Builds a generated dataclass from decoded JSON."""
|
|
65
|
+
if not isinstance(value, dict):
|
|
66
|
+
raise TypeError(f"expected an object for {cls.__name__}, got {type(value).__name__}")
|
|
67
|
+
hints = _field_types(cls)
|
|
68
|
+
arguments: dict[str, Any] = {}
|
|
69
|
+
for field in dataclasses.fields(cls): # type: ignore[arg-type]
|
|
70
|
+
annotation = hints[field.name]
|
|
71
|
+
if field.name in value:
|
|
72
|
+
arguments[field.name] = _value(annotation, value[field.name])
|
|
73
|
+
elif field.default is dataclasses.MISSING and field.default_factory is dataclasses.MISSING:
|
|
74
|
+
arguments[field.name] = _zero(annotation)
|
|
75
|
+
return cls(**arguments)
|