digestore 0.2.1__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.
@@ -0,0 +1 @@
1
+ 3.12
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 minamik
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,106 @@
1
+ Metadata-Version: 2.5
2
+ Name: digestore
3
+ Version: 0.2.1
4
+ Summary: A content-addressed store keyed by the sha256 of the stored bytes
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.12
8
+ Description-Content-Type: text/markdown
9
+
10
+ # digestore
11
+
12
+ digestore is a Python library for a content-addressed store keyed by the sha256 of the stored bytes.
13
+
14
+ Requires Python 3.12 or later. Files are stored in a local directory you choose; separate
15
+ applications can share a directory or use independent stores. The library has no runtime
16
+ dependencies.
17
+
18
+ ## Installation
19
+
20
+ Install a tagged version with uv, replacing the repository URL placeholder:
21
+
22
+ ```sh
23
+ uv add "digestore @ git+<PUBLIC_REPOSITORY_URL>@v0.2.0"
24
+ ```
25
+
26
+ ## Usage
27
+
28
+ ```python
29
+ import hashlib
30
+ import io
31
+ from datetime import timedelta
32
+ from pathlib import Path
33
+
34
+ from digestore import DigestMismatchError, Store
35
+
36
+ store = Store(Path("./content"))
37
+ data = b"hello"
38
+ expected = hashlib.sha256(data).hexdigest()
39
+ result = store.put(io.BytesIO(data), expected=expected)
40
+ print(result.sha256, result.size)
41
+
42
+ try:
43
+ store.put(io.BytesIO(b"different bytes"), expected=expected)
44
+ except DigestMismatchError as error:
45
+ assert error.expected == expected
46
+ assert error.actual == hashlib.sha256(b"different bytes").hexdigest()
47
+
48
+ with store.open(result.sha256) as content:
49
+ assert content.read() == b"hello"
50
+
51
+ assert store.exists(result.sha256)
52
+ assert store.verify(result.sha256)
53
+
54
+ with store.materialize(result.sha256, suffix=".txt") as path:
55
+ assert path.name.endswith(".txt")
56
+ assert path.read_bytes() == b"hello"
57
+
58
+ assert not path.exists()
59
+ assert set(store.keys()) == {result.sha256}
60
+
61
+ # Choose an age longer than any active put or borrowed path needs.
62
+ removed = store.prune(older_than=timedelta(days=1))
63
+ assert removed == 0
64
+
65
+ assert store.delete(result.sha256)
66
+ assert not store.exists(result.sha256)
67
+ assert list(store.keys()) == []
68
+ ```
69
+
70
+ `put` accepts a readable binary stream and leaves it open. It returns an immutable
71
+ `PutResult` with `sha256` and `size` attributes. Repeated content shares the existing
72
+ file at `<store>/<first two hash characters>/<full hash>`. Concurrent processes and
73
+ threads can put content into the same store.
74
+
75
+ Pass `expected` to require a particular sha256. A mismatch removes the temporary
76
+ file, leaves stored content untouched, and raises `DigestMismatchError`, a
77
+ `ValueError` with `expected` and `actual` hash attributes. Invalid expected hashes
78
+ raise `ValueError` before the stream is read.
79
+
80
+ Keys must contain exactly 64 lowercase hexadecimal characters. An invalid key raises
81
+ `ValueError`. `open`, `verify`, and entering `materialize` raise `NotFoundError` (a
82
+ `LookupError`) for missing content. `exists` and `delete` return `False` for a missing
83
+ key. Verification reports whether the bytes still match their key without modifying
84
+ the file.
85
+
86
+ Stored files have permission `0444` on macOS and Linux. On Windows the library does
87
+ not set the read-only attribute. Treat stored and borrowed content as immutable.
88
+
89
+ `materialize` creates a separate name in `<store>/tmp/` and lends its `Path` for the
90
+ `with` block. It uses a hard link to avoid copying data, or a copy when the
91
+ filesystem cannot create the link. The name is removed on exit, including when the
92
+ block raises an exception, while the stored file is kept. Deleting the stored key
93
+ during the block leaves the borrowed path readable until exit. An optional `suffix`
94
+ must start with `.` and contain no `/`, `\`, or NUL characters; invalid suffixes
95
+ raise `ValueError`. Close files opened through the borrowed path before exiting
96
+ the block. On Windows, deletion is retried for up to one second; if it remains
97
+ blocked, the name is left in `tmp/` and a `RuntimeWarning` is issued.
98
+
99
+ `prune(older_than)` removes temporary files and borrowed names older than the given
100
+ `datetime.timedelta` and returns how many it removed. It reads creation timestamps
101
+ from names, rather than file modification times, and leaves stored content and
102
+ unrecognized names untouched. The age has no default: choose a duration longer
103
+ than any active writer or reader needs. `keys()` yields the keys matching the
104
+ storage layout, excluding `tmp/` and other files; its order is unspecified.
105
+
106
+ The application decides when stored content may be deleted.
@@ -0,0 +1,97 @@
1
+ # digestore
2
+
3
+ digestore is a Python library for a content-addressed store keyed by the sha256 of the stored bytes.
4
+
5
+ Requires Python 3.12 or later. Files are stored in a local directory you choose; separate
6
+ applications can share a directory or use independent stores. The library has no runtime
7
+ dependencies.
8
+
9
+ ## Installation
10
+
11
+ Install a tagged version with uv, replacing the repository URL placeholder:
12
+
13
+ ```sh
14
+ uv add "digestore @ git+<PUBLIC_REPOSITORY_URL>@v0.2.0"
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ ```python
20
+ import hashlib
21
+ import io
22
+ from datetime import timedelta
23
+ from pathlib import Path
24
+
25
+ from digestore import DigestMismatchError, Store
26
+
27
+ store = Store(Path("./content"))
28
+ data = b"hello"
29
+ expected = hashlib.sha256(data).hexdigest()
30
+ result = store.put(io.BytesIO(data), expected=expected)
31
+ print(result.sha256, result.size)
32
+
33
+ try:
34
+ store.put(io.BytesIO(b"different bytes"), expected=expected)
35
+ except DigestMismatchError as error:
36
+ assert error.expected == expected
37
+ assert error.actual == hashlib.sha256(b"different bytes").hexdigest()
38
+
39
+ with store.open(result.sha256) as content:
40
+ assert content.read() == b"hello"
41
+
42
+ assert store.exists(result.sha256)
43
+ assert store.verify(result.sha256)
44
+
45
+ with store.materialize(result.sha256, suffix=".txt") as path:
46
+ assert path.name.endswith(".txt")
47
+ assert path.read_bytes() == b"hello"
48
+
49
+ assert not path.exists()
50
+ assert set(store.keys()) == {result.sha256}
51
+
52
+ # Choose an age longer than any active put or borrowed path needs.
53
+ removed = store.prune(older_than=timedelta(days=1))
54
+ assert removed == 0
55
+
56
+ assert store.delete(result.sha256)
57
+ assert not store.exists(result.sha256)
58
+ assert list(store.keys()) == []
59
+ ```
60
+
61
+ `put` accepts a readable binary stream and leaves it open. It returns an immutable
62
+ `PutResult` with `sha256` and `size` attributes. Repeated content shares the existing
63
+ file at `<store>/<first two hash characters>/<full hash>`. Concurrent processes and
64
+ threads can put content into the same store.
65
+
66
+ Pass `expected` to require a particular sha256. A mismatch removes the temporary
67
+ file, leaves stored content untouched, and raises `DigestMismatchError`, a
68
+ `ValueError` with `expected` and `actual` hash attributes. Invalid expected hashes
69
+ raise `ValueError` before the stream is read.
70
+
71
+ Keys must contain exactly 64 lowercase hexadecimal characters. An invalid key raises
72
+ `ValueError`. `open`, `verify`, and entering `materialize` raise `NotFoundError` (a
73
+ `LookupError`) for missing content. `exists` and `delete` return `False` for a missing
74
+ key. Verification reports whether the bytes still match their key without modifying
75
+ the file.
76
+
77
+ Stored files have permission `0444` on macOS and Linux. On Windows the library does
78
+ not set the read-only attribute. Treat stored and borrowed content as immutable.
79
+
80
+ `materialize` creates a separate name in `<store>/tmp/` and lends its `Path` for the
81
+ `with` block. It uses a hard link to avoid copying data, or a copy when the
82
+ filesystem cannot create the link. The name is removed on exit, including when the
83
+ block raises an exception, while the stored file is kept. Deleting the stored key
84
+ during the block leaves the borrowed path readable until exit. An optional `suffix`
85
+ must start with `.` and contain no `/`, `\`, or NUL characters; invalid suffixes
86
+ raise `ValueError`. Close files opened through the borrowed path before exiting
87
+ the block. On Windows, deletion is retried for up to one second; if it remains
88
+ blocked, the name is left in `tmp/` and a `RuntimeWarning` is issued.
89
+
90
+ `prune(older_than)` removes temporary files and borrowed names older than the given
91
+ `datetime.timedelta` and returns how many it removed. It reads creation timestamps
92
+ from names, rather than file modification times, and leaves stored content and
93
+ unrecognized names untouched. The age has no default: choose a duration longer
94
+ than any active writer or reader needs. `keys()` yields the keys matching the
95
+ storage layout, excluding `tmp/` and other files; its order is unspecified.
96
+
97
+ The application decides when stored content may be deleted.
@@ -0,0 +1,45 @@
1
+ [project]
2
+ name = "digestore"
3
+ dynamic = ["version"]
4
+ description = "A content-addressed store keyed by the sha256 of the stored bytes"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.12"
9
+ dependencies = []
10
+
11
+ [dependency-groups]
12
+ dev = ["pytest>=8", "pytest-xdist>=3", "ruff>=0.5"]
13
+
14
+ [build-system]
15
+ requires = ["hatchling", "hatch-vcs"]
16
+ build-backend = "hatchling.build"
17
+
18
+ [tool.hatch.version]
19
+ source = "vcs"
20
+
21
+ [tool.hatch.build.targets.wheel]
22
+ packages = ["src/digestore"]
23
+
24
+ [tool.hatch.build.targets.sdist]
25
+ include = [
26
+ "/src/",
27
+ "/tests/",
28
+ "/pyproject.toml",
29
+ "/uv.lock",
30
+ "/.python-version",
31
+ "/README.md",
32
+ "/LICENSE",
33
+ ]
34
+
35
+ [tool.ruff]
36
+ line-length = 100
37
+ target-version = "py312"
38
+
39
+ [tool.ruff.lint]
40
+ select = ["E", "F", "I", "UP", "B", "SIM"]
41
+
42
+ [tool.pytest.ini_options]
43
+ testpaths = ["tests"]
44
+ addopts = "--strict-markers"
45
+ markers = ["req(id): adopted specification item verified by the test"]
@@ -0,0 +1,5 @@
1
+ """Store bytes by their sha256 content hash."""
2
+
3
+ from ._store import DigestMismatchError, NotFoundError, PutResult, Store
4
+
5
+ __all__ = ["Store", "PutResult", "NotFoundError", "DigestMismatchError"]
@@ -0,0 +1,274 @@
1
+ """Local storage of complete, immutable content files."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import os
7
+ import re
8
+ import shutil
9
+ import stat
10
+ import tempfile
11
+ import time
12
+ import uuid
13
+ import warnings
14
+ from collections.abc import Iterator
15
+ from contextlib import contextmanager
16
+ from dataclasses import dataclass
17
+ from datetime import timedelta
18
+ from pathlib import Path
19
+ from typing import BinaryIO, Protocol
20
+
21
+ if os.name != "nt":
22
+ import fcntl
23
+
24
+ _CHUNK_SIZE = 1024 * 1024
25
+ _READ_BITS = stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH
26
+ _KEY = re.compile(r"[0-9a-f]{64}")
27
+ _BUCKET = re.compile(r"[0-9a-f]{2}")
28
+ _TEMPORARY_NAME = re.compile(
29
+ r"(?P<kind>put|lend)-(?P<created>[0-9]+)-[a-zA-Z0-9_-]+(?P<suffix>\.[^/\\\x00]*)?"
30
+ )
31
+
32
+
33
+ class _BinaryReader(Protocol):
34
+ def read(self, size: int, /) -> bytes: ...
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class PutResult:
39
+ """The sha256 key and byte count of a stored stream."""
40
+
41
+ sha256: str
42
+ size: int
43
+
44
+
45
+ class NotFoundError(LookupError):
46
+ """The requested key has no file in the store."""
47
+
48
+
49
+ class DigestMismatchError(ValueError):
50
+ """The stream's sha256 differs from its expected hash."""
51
+
52
+ def __init__(self, expected: str, actual: str) -> None:
53
+ self.expected = expected
54
+ self.actual = actual
55
+ super().__init__(f"expected sha256 {expected}, got {actual}")
56
+
57
+
58
+ def _validate_key(key: str) -> None:
59
+ if not isinstance(key, str) or _KEY.fullmatch(key) is None:
60
+ raise ValueError("key must contain exactly 64 lowercase hexadecimal characters")
61
+
62
+
63
+ def _sync_directory(path: Path) -> None:
64
+ if os.name != "nt":
65
+ fd = os.open(path, os.O_RDONLY)
66
+ try:
67
+ os.fsync(fd)
68
+ finally:
69
+ os.close(fd)
70
+
71
+
72
+ def _make_directory(path: Path) -> None:
73
+ """Persist new directories and their links from existing ancestors."""
74
+ if not path.is_dir():
75
+ _make_directory(path.parent)
76
+ path.mkdir(exist_ok=True)
77
+ _sync_directory(path.parent)
78
+
79
+
80
+ def _unlink(path: Path) -> bool:
81
+ try:
82
+ if os.name == "nt":
83
+ os.chmod(path, stat.S_IREAD | stat.S_IWRITE)
84
+ path.unlink()
85
+ except FileNotFoundError:
86
+ return False
87
+ return True
88
+
89
+
90
+ def _remove_borrowed_name(path: Path) -> None:
91
+ deadline = time.monotonic() + 1.0
92
+ while True:
93
+ try:
94
+ _unlink(path)
95
+ return
96
+ except PermissionError:
97
+ if os.name != "nt":
98
+ raise
99
+ remaining = deadline - time.monotonic()
100
+ if remaining <= 0:
101
+ warnings.warn(
102
+ f"could not remove borrowed file {path}; it remains for later pruning",
103
+ RuntimeWarning,
104
+ stacklevel=3,
105
+ )
106
+ return
107
+ time.sleep(min(0.1, remaining))
108
+
109
+
110
+ def _publish(temporary: Path, target: Path) -> None:
111
+ _make_directory(target.parent)
112
+ directory_fd = None
113
+ try:
114
+ if os.name != "nt":
115
+ directory_fd = os.open(target.parent, os.O_RDONLY)
116
+ # Separate opens contend across both threads and processes.
117
+ fcntl.flock(directory_fd, fcntl.LOCK_EX)
118
+ if target.exists():
119
+ return
120
+ published = False
121
+ try:
122
+ try:
123
+ os.rename(temporary, target)
124
+ except FileExistsError:
125
+ if os.name == "nt":
126
+ return
127
+ raise
128
+ published = True
129
+ if directory_fd is not None:
130
+ os.fsync(directory_fd)
131
+ except BaseException:
132
+ if published:
133
+ _unlink(target)
134
+ raise
135
+ finally:
136
+ if directory_fd is not None:
137
+ # Closing the descriptor also releases its advisory lock.
138
+ os.close(directory_fd)
139
+
140
+
141
+ class Store:
142
+ """A local directory holding files under their sha256 keys."""
143
+
144
+ def __init__(self, path: str | os.PathLike[str]) -> None:
145
+ self._root = Path(path)
146
+
147
+ def _path(self, key: str) -> Path:
148
+ _validate_key(key)
149
+ return self._root / key[:2] / key
150
+
151
+ def put(self, stream: _BinaryReader, expected: str | None = None) -> PutResult:
152
+ """Store a stream, checking an optional expected sha256 without closing it."""
153
+ if expected is not None:
154
+ _validate_key(expected)
155
+ temporary_directory = self._root / "tmp"
156
+ _make_directory(temporary_directory)
157
+ fd, name = tempfile.mkstemp(dir=temporary_directory, prefix=f"put-{time.time_ns()}-")
158
+ temporary = Path(name)
159
+ try:
160
+ digest = hashlib.sha256()
161
+ size = 0
162
+ with os.fdopen(fd, "wb") as destination:
163
+ while chunk := stream.read(_CHUNK_SIZE):
164
+ destination.write(chunk)
165
+ digest.update(chunk)
166
+ size += len(chunk)
167
+ destination.flush()
168
+ if os.name != "nt":
169
+ os.chmod(temporary, _READ_BITS)
170
+ os.fsync(destination.fileno())
171
+ key = digest.hexdigest()
172
+ if expected is not None and key != expected:
173
+ raise DigestMismatchError(expected, key)
174
+ _publish(temporary, self._root / key[:2] / key)
175
+ except BaseException:
176
+ _unlink(temporary)
177
+ raise
178
+ _unlink(temporary)
179
+ return PutResult(sha256=key, size=size)
180
+
181
+ def open(self, key: str) -> BinaryIO:
182
+ """Open the stored content for binary reading, or raise NotFoundError."""
183
+ path = self._path(key)
184
+ try:
185
+ return path.open("rb")
186
+ except FileNotFoundError as error:
187
+ raise NotFoundError(key) from error
188
+
189
+ def exists(self, key: str) -> bool:
190
+ """Return whether the key has a file in the store."""
191
+ return self._path(key).is_file()
192
+
193
+ def verify(self, key: str) -> bool:
194
+ """Rehash the file and report whether its content still matches its key."""
195
+ digest = hashlib.sha256()
196
+ with self.open(key) as content:
197
+ while chunk := content.read(_CHUNK_SIZE):
198
+ digest.update(chunk)
199
+ return digest.hexdigest() == key
200
+
201
+ def delete(self, key: str) -> bool:
202
+ """Delete the file if present and return whether a file was removed."""
203
+ return _unlink(self._path(key))
204
+
205
+ def prune(self, older_than: timedelta) -> int:
206
+ """Remove expired temporary files by their named creation times and return a count."""
207
+ cutoff = time.time_ns() - (older_than // timedelta(microseconds=1)) * 1000
208
+ try:
209
+ entries = os.scandir(self._root / "tmp")
210
+ except FileNotFoundError:
211
+ return 0
212
+ removed = 0
213
+ with entries:
214
+ for entry in entries:
215
+ match = _TEMPORARY_NAME.fullmatch(entry.name)
216
+ if match is None or (match["kind"] == "put" and match["suffix"] is not None):
217
+ continue
218
+ if int(match["created"]) >= cutoff or not entry.is_file():
219
+ continue
220
+ try:
221
+ if _unlink(Path(entry.path)):
222
+ removed += 1
223
+ except PermissionError:
224
+ if os.name != "nt":
225
+ raise
226
+ return removed
227
+
228
+ def keys(self) -> Iterator[str]:
229
+ """Yield file names matching the sha256 layout without creating the store."""
230
+ try:
231
+ buckets = os.scandir(self._root)
232
+ except FileNotFoundError:
233
+ return
234
+ with buckets:
235
+ for bucket in buckets:
236
+ if _BUCKET.fullmatch(bucket.name) is None or not bucket.is_dir():
237
+ continue
238
+ with os.scandir(bucket.path) as entries:
239
+ for entry in entries:
240
+ if (
241
+ _KEY.fullmatch(entry.name) is not None
242
+ and entry.name.startswith(bucket.name)
243
+ and entry.is_file()
244
+ ):
245
+ yield entry.name
246
+
247
+ @contextmanager
248
+ def materialize(self, key: str, suffix: str | None = None) -> Iterator[Path]:
249
+ """Lend a temporary hard link or copy and remove its name after the block."""
250
+ if suffix is not None and (
251
+ not isinstance(suffix, str)
252
+ or not suffix.startswith(".")
253
+ or any(character in suffix for character in ("/", "\\", "\0"))
254
+ ):
255
+ raise ValueError("suffix must start with '.' and contain no path separators or NUL")
256
+ target = self._path(key)
257
+ if not target.is_file():
258
+ raise NotFoundError(key)
259
+ temporary_directory = self._root / "tmp"
260
+ _make_directory(temporary_directory)
261
+ path = temporary_directory / f"lend-{time.time_ns()}-{uuid.uuid4().hex}{suffix or ''}"
262
+ try:
263
+ try:
264
+ os.link(target, path)
265
+ except FileNotFoundError as error:
266
+ raise NotFoundError(key) from error
267
+ except OSError:
268
+ try:
269
+ shutil.copyfile(target, path)
270
+ except FileNotFoundError as error:
271
+ raise NotFoundError(key) from error
272
+ yield path
273
+ finally:
274
+ _remove_borrowed_name(path)
File without changes