litebackup 1.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 (35) hide show
  1. litebackup-1.1.0/.gitignore +10 -0
  2. litebackup-1.1.0/LICENSE +21 -0
  3. litebackup-1.1.0/PKG-INFO +174 -0
  4. litebackup-1.1.0/README.md +148 -0
  5. litebackup-1.1.0/pyproject.toml +76 -0
  6. litebackup-1.1.0/scripts/wheel_hook.py +32 -0
  7. litebackup-1.1.0/src/litebackup/__init__.py +94 -0
  8. litebackup-1.1.0/src/litebackup/_async_transport.py +128 -0
  9. litebackup-1.1.0/src/litebackup/_binary.py +111 -0
  10. litebackup-1.1.0/src/litebackup/_credential.py +53 -0
  11. litebackup-1.1.0/src/litebackup/_decode.py +75 -0
  12. litebackup-1.1.0/src/litebackup/_failover.py +476 -0
  13. litebackup-1.1.0/src/litebackup/_foreground.py +266 -0
  14. litebackup-1.1.0/src/litebackup/_generated/__init__.py +1 -0
  15. litebackup-1.1.0/src/litebackup/_generated/error_codes.py +34 -0
  16. litebackup-1.1.0/src/litebackup/_generated/models.py +639 -0
  17. litebackup-1.1.0/src/litebackup/_launch.py +121 -0
  18. litebackup-1.1.0/src/litebackup/_paths.py +82 -0
  19. litebackup-1.1.0/src/litebackup/_pool.py +1142 -0
  20. litebackup-1.1.0/src/litebackup/_transport.py +201 -0
  21. litebackup-1.1.0/src/litebackup/_umask.py +55 -0
  22. litebackup-1.1.0/src/litebackup/_version.py +7 -0
  23. litebackup-1.1.0/src/litebackup/_wire.py +456 -0
  24. litebackup-1.1.0/src/litebackup/client.py +958 -0
  25. litebackup-1.1.0/src/litebackup/errors.py +118 -0
  26. litebackup-1.1.0/src/litebackup/integrations/__init__.py +8 -0
  27. litebackup-1.1.0/src/litebackup/integrations/_sqlite_uri.py +67 -0
  28. litebackup-1.1.0/src/litebackup/integrations/aiosqlite.py +46 -0
  29. litebackup-1.1.0/src/litebackup/integrations/django/__init__.py +19 -0
  30. litebackup-1.1.0/src/litebackup/integrations/django/apps.py +80 -0
  31. litebackup-1.1.0/src/litebackup/integrations/fastapi.py +78 -0
  32. litebackup-1.1.0/src/litebackup/integrations/sqlalchemy.py +159 -0
  33. litebackup-1.1.0/src/litebackup/integrations/sqlite3.py +57 -0
  34. litebackup-1.1.0/src/litebackup/py.typed +0 -0
  35. litebackup-1.1.0/src/litebackup/release.py +122 -0
@@ -0,0 +1,10 @@
1
+ node_modules/
2
+ dist/
3
+ *.tgz
4
+ typescript/npm/*/bin/
5
+ .venv/
6
+ python/src/litebackup/_bin/
7
+ __pycache__/
8
+ .mypy_cache/
9
+ .ruff_cache/
10
+ .pytest_cache/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Litebackup
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,174 @@
1
+ Metadata-Version: 2.4
2
+ Name: litebackup
3
+ Version: 1.1.0
4
+ Summary: Back up, replicate, and restore SQLite databases with Litebackup
5
+ Project-URL: Homepage, https://litebackup.com/sdk
6
+ Project-URL: Source, https://github.com/litebackup/sdk
7
+ Project-URL: Issues, https://github.com/litebackup/sdk/issues
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Operating System :: MacOS
11
+ Classifier: Operating System :: POSIX :: Linux
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Database
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.11
16
+ Requires-Dist: h11<1,>=0.14
17
+ Provides-Extra: aiosqlite
18
+ Requires-Dist: aiosqlite>=0.20; extra == 'aiosqlite'
19
+ Provides-Extra: django
20
+ Requires-Dist: django>=4.2; extra == 'django'
21
+ Provides-Extra: release
22
+ Requires-Dist: cryptography>=42; extra == 'release'
23
+ Provides-Extra: sqlalchemy
24
+ Requires-Dist: sqlalchemy>=2.0; extra == 'sqlalchemy'
25
+ Description-Content-Type: text/markdown
26
+
27
+ # Litebackup for Python
28
+
29
+ Back up, replicate, and restore SQLite databases with your Litebackup server
30
+ and bucket. Python 3.11 or later on Linux or macOS.
31
+
32
+ ```sh
33
+ pip install litebackup
34
+ export LITEBACKUP_API_KEY='JOIN_TOKEN@your-instance.litebackup.cloud'
35
+ ```
36
+
37
+ `LITEBACKUP_API_KEY` is the value from **Machines → Add machine**, or an API
38
+ key followed by @ and your server address. Wheels for
39
+ Linux (glibc and musl) and macOS, on x64 and arm64, include the `litebackup`
40
+ client, which the SDK starts on first use. On other platforms pip installs
41
+ the source package, which uses an installed `litebackup` command: install it
42
+ with `curl -fsSL https://litebackup.com/cli.sh | bash`, or set `LITEBACKUP_PATH`.
43
+
44
+ ## Back up an app's database
45
+
46
+ ```python
47
+ import os
48
+ import sqlite3
49
+
50
+ from litebackup import Litebackup
51
+
52
+ os.makedirs("data", exist_ok=True)
53
+ path = "data/app.sqlite"
54
+ connection = sqlite3.connect(path)
55
+ with Litebackup() as litebackup:
56
+ rule = litebackup.backups.start(path)
57
+ print(rule.id, rule.name)
58
+ ```
59
+
60
+ Code that has the connection but not its path can ask SQLite which file it
61
+ opened. `database_path(connection)` from `litebackup.integrations.sqlite3` does
62
+ this and raises `invalid_argument` for an in-memory database:
63
+
64
+ ```python
65
+ import os
66
+ import sqlite3
67
+
68
+ from litebackup import Litebackup
69
+
70
+ os.makedirs("data", exist_ok=True)
71
+ connection = sqlite3.connect("data/app.sqlite")
72
+ with Litebackup() as litebackup:
73
+ (file,) = connection.execute("SELECT file FROM pragma_database_list WHERE name = 'main'").fetchone()
74
+ if file: # an empty file means in-memory: nothing to back up
75
+ litebackup.backups.start(file)
76
+ ```
77
+
78
+ `backups.start` returns once the daemon saved the rule; uploads run in the
79
+ background. Call it on every start: the same path and settings return the
80
+ saved rule, and other settings raise `LitebackupError` with code `rule_exists` and
81
+ the saved rule in `details["rule"]`.
82
+
83
+ | Integration | Extra | Use |
84
+ | --- | --- | --- |
85
+ | `litebackup.integrations.sqlite3` | | `database_path(connection, schema="main")`, `adapter()` |
86
+ | `litebackup.integrations.aiosqlite` | `aiosqlite` | `await database_path(connection)`, `adapter()` |
87
+ | `litebackup.integrations.sqlalchemy` | `sqlalchemy` | `database_path(connection \| engine \| url)`, `await async_database_path(async_connection \| async_engine)`; for an engine with a custom `creator`, pass a connection |
88
+ | `litebackup.integrations.django` | `django` | Add to `INSTALLED_APPS` and set `LITEBACKUP = {"databases": {"default": {}}}` |
89
+ | `litebackup.integrations.fastapi` | | `FastAPI(lifespan=backup_lifespan("/var/lib/app/main.sqlite"))` |
90
+ | `litebackup.release` | `release` | `find_release(metadata)` verifies signed release metadata |
91
+
92
+ ## Lease a database that moves between machines
93
+
94
+ ```python
95
+ from litebackup import Litebackup
96
+ from litebackup.integrations.sqlite3 import adapter
97
+
98
+ with Litebackup() as litebackup, litebackup.databases.pool(adapter=adapter()) as pool:
99
+ with pool.lease("agents/42.sqlite", path="data/agents/42.sqlite", durability="server") as db:
100
+ db.execute("CREATE TABLE IF NOT EXISTS steps (body TEXT)")
101
+ db.execute("INSERT INTO steps (body) VALUES (?)", ("tests passed",))
102
+ db.commit()
103
+ ```
104
+
105
+ The first lease acquires the database's write lock, creating an empty file at
106
+ `path` when nothing is there, and opens it. The pool keeps the lock and the
107
+ open connection for later leases of the same name, which run one at a time,
108
+ until no lease used it for `idle_release` (a minute by default; 0 keeps it), or
109
+ you call `pool.release(name)` or `pool.close()`. Each release closes the
110
+ connection and returns once your server has the final version.
111
+
112
+ Your app coordinates handovers between machines: while one machine keeps the
113
+ lease, another machine's lease fails with `lock_unavailable`, or with
114
+ `lock_timeout=30` waits up to 30 seconds and succeeds once the first releases
115
+ it. A lease on a database whose lock this machine lost meanwhile raises
116
+ `lock_lost` before its block runs; the next lease acquires it again.
117
+
118
+ With `durability="server"` a lease returns once your server has what the block
119
+ committed; `"cloud"` waits for the bucket too. The adapter opens existing files
120
+ only and rolls back what the block did not commit; it never commits for you. A
121
+ block that raises keeps the lease, and the release that ends it does not
122
+ offload. A failed close does not release: the database stays acquired and the
123
+ error is a `LeaseCleanupError` (`lease_cleanup_failed`). Several failures
124
+ raise an `ExceptionGroup`.
125
+
126
+ For a database a backup rule on this machine covers, `pool.use(name)` yields
127
+ its connection, bringing back an offloaded copy first and keeping it open
128
+ between calls. A rollback-journal database under a rule saved with
129
+ `offload_rollback_journal` is closed as soon as its last `use` block exits
130
+ instead, so the rule never offloads it under an open connection.
131
+
132
+ ## asyncio
133
+
134
+ `AsyncLitebackup` has the same groups, awaited, and async iterators. The
135
+ aiosqlite adapter below needs its extra: `pip install 'litebackup[aiosqlite]'`.
136
+
137
+ ```python
138
+ import asyncio
139
+
140
+ from litebackup import AsyncLitebackup
141
+ from litebackup.integrations.aiosqlite import adapter
142
+
143
+
144
+ async def main() -> None:
145
+ async with AsyncLitebackup() as litebackup:
146
+ async for database in litebackup.databases.all():
147
+ print(database.name, database.state)
148
+ async with (
149
+ litebackup.databases.pool(adapter=adapter()) as pool,
150
+ pool.lease("agents/42.sqlite", path="data/agents/42.sqlite") as db,
151
+ ):
152
+ await db.execute("CREATE TABLE IF NOT EXISTS steps (body TEXT)")
153
+ await db.execute("INSERT INTO steps (body) VALUES (?)", ("tests passed",))
154
+ await db.commit()
155
+
156
+
157
+ asyncio.run(main())
158
+ ```
159
+
160
+ Cancelling a task stops its local wait; the daemon may still finish the
161
+ operation, and `asyncio.CancelledError` propagates. A cancelled lease keeps
162
+ the lock, and the release that ends it does not offload; a block that catches
163
+ the cancellation and returns still counts as cancelled. `close()` waits for
164
+ active blocks, and a cancelled `close()` keeps releasing; await it again to
165
+ see its result.
166
+
167
+ ## Everything else
168
+
169
+ The groups are `backups`, `rules`, `databases`, `replicas`,
170
+ `events`, `session`, and `failovers`, with keyword-only arguments. Durations
171
+ are seconds or `timedelta`. Results are frozen dataclasses with the API's
172
+ field names. `close()` never stops the daemon. See the
173
+ [SDK reference](https://github.com/litebackup/sdk/blob/main/docs/sdk-reference.md)
174
+ and [integrations](https://github.com/litebackup/sdk/blob/main/docs/sqlite-integrations.md).
@@ -0,0 +1,148 @@
1
+ # Litebackup for Python
2
+
3
+ Back up, replicate, and restore SQLite databases with your Litebackup server
4
+ and bucket. Python 3.11 or later on Linux or macOS.
5
+
6
+ ```sh
7
+ pip install litebackup
8
+ export LITEBACKUP_API_KEY='JOIN_TOKEN@your-instance.litebackup.cloud'
9
+ ```
10
+
11
+ `LITEBACKUP_API_KEY` is the value from **Machines → Add machine**, or an API
12
+ key followed by @ and your server address. Wheels for
13
+ Linux (glibc and musl) and macOS, on x64 and arm64, include the `litebackup`
14
+ client, which the SDK starts on first use. On other platforms pip installs
15
+ the source package, which uses an installed `litebackup` command: install it
16
+ with `curl -fsSL https://litebackup.com/cli.sh | bash`, or set `LITEBACKUP_PATH`.
17
+
18
+ ## Back up an app's database
19
+
20
+ ```python
21
+ import os
22
+ import sqlite3
23
+
24
+ from litebackup import Litebackup
25
+
26
+ os.makedirs("data", exist_ok=True)
27
+ path = "data/app.sqlite"
28
+ connection = sqlite3.connect(path)
29
+ with Litebackup() as litebackup:
30
+ rule = litebackup.backups.start(path)
31
+ print(rule.id, rule.name)
32
+ ```
33
+
34
+ Code that has the connection but not its path can ask SQLite which file it
35
+ opened. `database_path(connection)` from `litebackup.integrations.sqlite3` does
36
+ this and raises `invalid_argument` for an in-memory database:
37
+
38
+ ```python
39
+ import os
40
+ import sqlite3
41
+
42
+ from litebackup import Litebackup
43
+
44
+ os.makedirs("data", exist_ok=True)
45
+ connection = sqlite3.connect("data/app.sqlite")
46
+ with Litebackup() as litebackup:
47
+ (file,) = connection.execute("SELECT file FROM pragma_database_list WHERE name = 'main'").fetchone()
48
+ if file: # an empty file means in-memory: nothing to back up
49
+ litebackup.backups.start(file)
50
+ ```
51
+
52
+ `backups.start` returns once the daemon saved the rule; uploads run in the
53
+ background. Call it on every start: the same path and settings return the
54
+ saved rule, and other settings raise `LitebackupError` with code `rule_exists` and
55
+ the saved rule in `details["rule"]`.
56
+
57
+ | Integration | Extra | Use |
58
+ | --- | --- | --- |
59
+ | `litebackup.integrations.sqlite3` | | `database_path(connection, schema="main")`, `adapter()` |
60
+ | `litebackup.integrations.aiosqlite` | `aiosqlite` | `await database_path(connection)`, `adapter()` |
61
+ | `litebackup.integrations.sqlalchemy` | `sqlalchemy` | `database_path(connection \| engine \| url)`, `await async_database_path(async_connection \| async_engine)`; for an engine with a custom `creator`, pass a connection |
62
+ | `litebackup.integrations.django` | `django` | Add to `INSTALLED_APPS` and set `LITEBACKUP = {"databases": {"default": {}}}` |
63
+ | `litebackup.integrations.fastapi` | | `FastAPI(lifespan=backup_lifespan("/var/lib/app/main.sqlite"))` |
64
+ | `litebackup.release` | `release` | `find_release(metadata)` verifies signed release metadata |
65
+
66
+ ## Lease a database that moves between machines
67
+
68
+ ```python
69
+ from litebackup import Litebackup
70
+ from litebackup.integrations.sqlite3 import adapter
71
+
72
+ with Litebackup() as litebackup, litebackup.databases.pool(adapter=adapter()) as pool:
73
+ with pool.lease("agents/42.sqlite", path="data/agents/42.sqlite", durability="server") as db:
74
+ db.execute("CREATE TABLE IF NOT EXISTS steps (body TEXT)")
75
+ db.execute("INSERT INTO steps (body) VALUES (?)", ("tests passed",))
76
+ db.commit()
77
+ ```
78
+
79
+ The first lease acquires the database's write lock, creating an empty file at
80
+ `path` when nothing is there, and opens it. The pool keeps the lock and the
81
+ open connection for later leases of the same name, which run one at a time,
82
+ until no lease used it for `idle_release` (a minute by default; 0 keeps it), or
83
+ you call `pool.release(name)` or `pool.close()`. Each release closes the
84
+ connection and returns once your server has the final version.
85
+
86
+ Your app coordinates handovers between machines: while one machine keeps the
87
+ lease, another machine's lease fails with `lock_unavailable`, or with
88
+ `lock_timeout=30` waits up to 30 seconds and succeeds once the first releases
89
+ it. A lease on a database whose lock this machine lost meanwhile raises
90
+ `lock_lost` before its block runs; the next lease acquires it again.
91
+
92
+ With `durability="server"` a lease returns once your server has what the block
93
+ committed; `"cloud"` waits for the bucket too. The adapter opens existing files
94
+ only and rolls back what the block did not commit; it never commits for you. A
95
+ block that raises keeps the lease, and the release that ends it does not
96
+ offload. A failed close does not release: the database stays acquired and the
97
+ error is a `LeaseCleanupError` (`lease_cleanup_failed`). Several failures
98
+ raise an `ExceptionGroup`.
99
+
100
+ For a database a backup rule on this machine covers, `pool.use(name)` yields
101
+ its connection, bringing back an offloaded copy first and keeping it open
102
+ between calls. A rollback-journal database under a rule saved with
103
+ `offload_rollback_journal` is closed as soon as its last `use` block exits
104
+ instead, so the rule never offloads it under an open connection.
105
+
106
+ ## asyncio
107
+
108
+ `AsyncLitebackup` has the same groups, awaited, and async iterators. The
109
+ aiosqlite adapter below needs its extra: `pip install 'litebackup[aiosqlite]'`.
110
+
111
+ ```python
112
+ import asyncio
113
+
114
+ from litebackup import AsyncLitebackup
115
+ from litebackup.integrations.aiosqlite import adapter
116
+
117
+
118
+ async def main() -> None:
119
+ async with AsyncLitebackup() as litebackup:
120
+ async for database in litebackup.databases.all():
121
+ print(database.name, database.state)
122
+ async with (
123
+ litebackup.databases.pool(adapter=adapter()) as pool,
124
+ pool.lease("agents/42.sqlite", path="data/agents/42.sqlite") as db,
125
+ ):
126
+ await db.execute("CREATE TABLE IF NOT EXISTS steps (body TEXT)")
127
+ await db.execute("INSERT INTO steps (body) VALUES (?)", ("tests passed",))
128
+ await db.commit()
129
+
130
+
131
+ asyncio.run(main())
132
+ ```
133
+
134
+ Cancelling a task stops its local wait; the daemon may still finish the
135
+ operation, and `asyncio.CancelledError` propagates. A cancelled lease keeps
136
+ the lock, and the release that ends it does not offload; a block that catches
137
+ the cancellation and returns still counts as cancelled. `close()` waits for
138
+ active blocks, and a cancelled `close()` keeps releasing; await it again to
139
+ see its result.
140
+
141
+ ## Everything else
142
+
143
+ The groups are `backups`, `rules`, `databases`, `replicas`,
144
+ `events`, `session`, and `failovers`, with keyword-only arguments. Durations
145
+ are seconds or `timedelta`. Results are frozen dataclasses with the API's
146
+ field names. `close()` never stops the daemon. See the
147
+ [SDK reference](https://github.com/litebackup/sdk/blob/main/docs/sdk-reference.md)
148
+ and [integrations](https://github.com/litebackup/sdk/blob/main/docs/sqlite-integrations.md).
@@ -0,0 +1,76 @@
1
+ [build-system]
2
+ requires = ["hatchling==1.27.0"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "litebackup"
7
+ version = "1.1.0"
8
+ description = "Back up, replicate, and restore SQLite databases with Litebackup"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.11"
13
+ dependencies = ["h11>=0.14,<1"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Operating System :: POSIX :: Linux",
17
+ "Operating System :: MacOS",
18
+ "Topic :: Database",
19
+ "Typing :: Typed",
20
+ ]
21
+
22
+ [project.optional-dependencies]
23
+ release = ["cryptography>=42"]
24
+ aiosqlite = ["aiosqlite>=0.20"]
25
+ sqlalchemy = ["sqlalchemy>=2.0"]
26
+ django = ["django>=4.2"]
27
+
28
+ [project.urls]
29
+ Homepage = "https://litebackup.com/sdk"
30
+ Source = "https://github.com/litebackup/sdk"
31
+ Issues = "https://github.com/litebackup/sdk/issues"
32
+
33
+ [dependency-groups]
34
+ dev = [
35
+ "pytest==8.4.2",
36
+ "pytest-asyncio==1.2.0",
37
+ "mypy==1.18.2",
38
+ "ruff==0.14.1",
39
+ "cryptography==46.0.3",
40
+ "aiosqlite==0.21.0",
41
+ "sqlalchemy==2.0.44",
42
+ "django==5.2.7",
43
+ "django-stubs==5.2.7",
44
+ "fastapi==0.120.0",
45
+ "uvicorn==0.38.0",
46
+ ]
47
+
48
+ [tool.hatch.build.targets.wheel]
49
+ packages = ["src/litebackup"]
50
+ exclude = ["src/litebackup/_bin"]
51
+
52
+ [tool.hatch.build.targets.wheel.hooks.custom]
53
+ path = "scripts/wheel_hook.py"
54
+
55
+ [tool.hatch.build.targets.sdist]
56
+ include = ["src/litebackup", "README.md", "LICENSE", "pyproject.toml", "scripts/wheel_hook.py"]
57
+ exclude = ["src/litebackup/_bin"]
58
+
59
+ [tool.pytest.ini_options]
60
+ testpaths = ["tests"]
61
+ asyncio_mode = "auto"
62
+ asyncio_default_fixture_loop_scope = "function"
63
+
64
+ [tool.mypy]
65
+ strict = true
66
+ python_version = "3.11"
67
+
68
+ [tool.ruff]
69
+ line-length = 140
70
+ target-version = "py311"
71
+ extend-exclude = ["src/litebackup/_generated"]
72
+
73
+ [tool.ruff.lint]
74
+ select = ["E", "F", "W", "I", "B", "UP", "SIM", "RUF", "ASYNC"]
75
+ # timeout arguments are the daemon's server-side timeouts, sent as timeout_millis, not local waits.
76
+ ignore = ["ASYNC109"]
@@ -0,0 +1,32 @@
1
+ """Hatchling build hook for platform wheels.
2
+
3
+ scripts/build-wheels sets LITEBACKUP_WHEEL_BINARY to a verified litebackup binary
4
+ and LITEBACKUP_WHEEL_PLATFORM to its wheel platform tag. The hook then ships the
5
+ binary as litebackup/_bin/litebackup and tags the wheel py3-none-<platform>. With
6
+ neither set, the build is the pure wheel or the sdist, which use the installed
7
+ litebackup command.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ from typing import Any
14
+
15
+ from hatchling.builders.hooks.plugin.interface import BuildHookInterface
16
+
17
+
18
+ class PlatformBinaryHook(BuildHookInterface): # type: ignore[type-arg]
19
+ PLUGIN_NAME = "custom"
20
+
21
+ def initialize(self, version: str, build_data: dict[str, Any]) -> None:
22
+ if self.target_name != "wheel":
23
+ return
24
+ binary = os.environ.get("LITEBACKUP_WHEEL_BINARY")
25
+ platform = os.environ.get("LITEBACKUP_WHEEL_PLATFORM")
26
+ if not binary and not platform:
27
+ return
28
+ if not binary or not platform or not os.path.isfile(binary):
29
+ raise RuntimeError("platform wheels need LITEBACKUP_WHEEL_BINARY (an existing file) and LITEBACKUP_WHEEL_PLATFORM")
30
+ build_data["pure_python"] = False
31
+ build_data["tag"] = f"py3-none-{platform}"
32
+ build_data["force_include"][binary] = "litebackup/_bin/litebackup"
@@ -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()