datadouble-files 0.0.3__py3-none-any.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.
- datadouble_files/__init__.py +98 -0
- datadouble_files/py.typed +0 -0
- datadouble_files/source.py +123 -0
- datadouble_files/tree.py +186 -0
- datadouble_files/working.py +178 -0
- datadouble_files-0.0.3.dist-info/METADATA +72 -0
- datadouble_files-0.0.3.dist-info/RECORD +10 -0
- datadouble_files-0.0.3.dist-info/WHEEL +4 -0
- datadouble_files-0.0.3.dist-info/entry_points.txt +2 -0
- datadouble_files-0.0.3.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""The files engine adapter for Datadouble.
|
|
5
|
+
|
|
6
|
+
It copies a spec's ``files`` (decision 97)::
|
|
7
|
+
|
|
8
|
+
files:
|
|
9
|
+
connection:
|
|
10
|
+
root: /srv/uploads # the tree, as Datadouble sees it
|
|
11
|
+
accept_inconsistent: true # no filesystem snapshot: copy each file as it is
|
|
12
|
+
select: # find tests for each top-level directory
|
|
13
|
+
avatars: -mtime -30
|
|
14
|
+
documents: -size -10M
|
|
15
|
+
exclude: [tmp, cache]
|
|
16
|
+
paths_from: # and the files the chosen rows name
|
|
17
|
+
table: customer_documents
|
|
18
|
+
path: documents/{customer_id}/{file_name}
|
|
19
|
+
cleanup: # shell, run in the copy's root
|
|
20
|
+
- find . -name '*.log' -delete
|
|
21
|
+
image: vendor/exiftool:13 # the image cleanup runs in
|
|
22
|
+
|
|
23
|
+
Each top-level directory is a table whose rows are its files, keyed by their
|
|
24
|
+
path from the root. Every top-level directory must be selected or excluded.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from collections.abc import Generator, Mapping
|
|
28
|
+
from contextlib import contextmanager
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
|
|
31
|
+
from pydantic import BaseModel, ConfigDict, JsonValue
|
|
32
|
+
|
|
33
|
+
from datadouble.engine import EngineError, ServerPlan, SourceSession, Tooling, WorkingDatabases
|
|
34
|
+
from datadouble.names import EngineName
|
|
35
|
+
from datadouble.planner import Capabilities
|
|
36
|
+
from datadouble.runtime import identity
|
|
37
|
+
from datadouble.settings import NoSettings, parse_settings
|
|
38
|
+
from datadouble.spec import ImageFormat
|
|
39
|
+
from datadouble_files.source import FilesSource
|
|
40
|
+
from datadouble_files.tree import ENGINE
|
|
41
|
+
from datadouble_files.working import DEFAULT_IMAGE, FilesWorking
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class FilesConnection(BaseModel):
|
|
45
|
+
"""The ``files.connection`` settings."""
|
|
46
|
+
|
|
47
|
+
model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
|
|
48
|
+
|
|
49
|
+
root: str
|
|
50
|
+
accept_inconsistent: bool = False
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class FilesEngine:
|
|
54
|
+
"""Implements :class:`datadouble.engine.EngineAdapter` for file trees."""
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def name(self) -> EngineName:
|
|
58
|
+
"""``files``."""
|
|
59
|
+
return ENGINE
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def owner(self) -> str:
|
|
63
|
+
"""Whoever runs Datadouble: copies are plain files, served by no server."""
|
|
64
|
+
return identity()
|
|
65
|
+
|
|
66
|
+
def capabilities(self) -> Capabilities:
|
|
67
|
+
"""Physical images and hooks (the cleanup commands); every directory is accounted for."""
|
|
68
|
+
return Capabilities(
|
|
69
|
+
formats=(ImageFormat.PHYSICAL,),
|
|
70
|
+
expressions=False,
|
|
71
|
+
nested=False,
|
|
72
|
+
hooks=True,
|
|
73
|
+
complete=True,
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
@contextmanager
|
|
77
|
+
def connect(self, connection: Mapping[str, JsonValue]) -> Generator[SourceSession]:
|
|
78
|
+
"""Open the tree."""
|
|
79
|
+
settings = parse_settings(FilesConnection, connection, "files connection")
|
|
80
|
+
yield FilesSource(Path(settings.root), accept_inconsistent=settings.accept_inconsistent)
|
|
81
|
+
|
|
82
|
+
def working(self, scratch: Path, tooling: Tooling, source_version: str) -> WorkingDatabases: # noqa: ARG002 - one layout version
|
|
83
|
+
"""Copies under ``scratch``; cleanup runs in ``tooling.image`` or a Debian image."""
|
|
84
|
+
parse_settings(NoSettings, tooling.server, "files server")
|
|
85
|
+
return FilesWorking(tooling.runtime, tooling.image or DEFAULT_IMAGE, scratch)
|
|
86
|
+
|
|
87
|
+
def server(self, image: Path, server_image: str | None) -> ServerPlan:
|
|
88
|
+
"""A file tree has no server; replicate it as a volume."""
|
|
89
|
+
message = (
|
|
90
|
+
f"{image.name}: a file tree has no server to start, in {server_image or 'any'} image;"
|
|
91
|
+
" its copies are its files"
|
|
92
|
+
)
|
|
93
|
+
raise EngineError(message)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def engine() -> FilesEngine:
|
|
97
|
+
"""The entry point named in ``datadouble.engines``."""
|
|
98
|
+
return FilesEngine()
|
|
File without changes
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""The source side: the tree's catalog, and the copy of the chosen files.
|
|
5
|
+
|
|
6
|
+
A file tree has no transactions. A consistent copy would need a filesystem
|
|
7
|
+
snapshot (btrfs, ZFS or LVM), which this version does not take, so the
|
|
8
|
+
extract runs only when the spec accepts an inconsistent copy
|
|
9
|
+
(``accept_inconsistent: true``), and the manifest says so: each file is
|
|
10
|
+
copied as it is when read.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import datetime as dt
|
|
14
|
+
import shutil
|
|
15
|
+
import time
|
|
16
|
+
from collections.abc import Generator, Iterable, Mapping
|
|
17
|
+
from contextlib import contextmanager
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from pydantic import BaseModel, ConfigDict
|
|
21
|
+
|
|
22
|
+
from datadouble.catalog import Catalog
|
|
23
|
+
from datadouble.engine import EngineError, ExtractResult, Snapshot, TableCount, Tooling, outermost
|
|
24
|
+
from datadouble.names import ColumnName, TableName
|
|
25
|
+
from datadouble.planner import Plan
|
|
26
|
+
from datadouble.subset import Condition, KeyTuple
|
|
27
|
+
from datadouble_files.tree import PATH, catalog, chosen
|
|
28
|
+
|
|
29
|
+
TREE = "tree"
|
|
30
|
+
"""The directory of an extract, working copy or image that holds the files."""
|
|
31
|
+
VERSION = "1"
|
|
32
|
+
"""The version of the tree's layout, which images record as their server version."""
|
|
33
|
+
INCONSISTENT = "none: each file as it was when copied"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Extracted(BaseModel):
|
|
37
|
+
"""What an extract holds, for ``load``."""
|
|
38
|
+
|
|
39
|
+
model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
|
|
40
|
+
|
|
41
|
+
tables: tuple[TableName, ...]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class FilesSnapshot:
|
|
45
|
+
"""Reads of the live tree; not a snapshot, as the spec accepted."""
|
|
46
|
+
|
|
47
|
+
def __init__(self, root: Path, as_of: dt.datetime) -> None:
|
|
48
|
+
"""Read ``root``; ``as_of`` is bound where find tests say ``:as_of``."""
|
|
49
|
+
self.root = root
|
|
50
|
+
self.as_of = as_of
|
|
51
|
+
self.opened = time.monotonic()
|
|
52
|
+
|
|
53
|
+
def project(
|
|
54
|
+
self, table: TableName, condition: Condition, columns: tuple[ColumnName, ...]
|
|
55
|
+
) -> Iterable[KeyTuple]:
|
|
56
|
+
"""The chosen files' paths; files have no other key."""
|
|
57
|
+
if columns != (PATH,):
|
|
58
|
+
message = f"files are chosen by path, not {', '.join(columns)}"
|
|
59
|
+
raise EngineError(message)
|
|
60
|
+
return {(path,) for path in chosen(self.root, table, condition, self.as_of)}
|
|
61
|
+
|
|
62
|
+
def extract(
|
|
63
|
+
self,
|
|
64
|
+
plan: Plan,
|
|
65
|
+
selections: Mapping[TableName, Condition],
|
|
66
|
+
directory: Path,
|
|
67
|
+
tooling: Tooling, # noqa: ARG002 - the copy needs no containers
|
|
68
|
+
) -> ExtractResult:
|
|
69
|
+
"""Copy the chosen files, keeping their paths and times."""
|
|
70
|
+
current = catalog(self.root)
|
|
71
|
+
if current.fingerprint() != plan.catalog_fingerprint:
|
|
72
|
+
message = "the tree's top-level directories changed since planning; plan again"
|
|
73
|
+
raise EngineError(message)
|
|
74
|
+
counts: list[TableCount] = []
|
|
75
|
+
for table in plan.extracted():
|
|
76
|
+
paths = sorted(chosen(self.root, table, selections[table], self.as_of))
|
|
77
|
+
for path in paths:
|
|
78
|
+
target = directory / TREE / path
|
|
79
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
80
|
+
shutil.copy2(self.root / path, target)
|
|
81
|
+
(directory / TREE / table.name).mkdir(parents=True, exist_ok=True)
|
|
82
|
+
counts.append(TableCount(table=table, rows=len(paths)))
|
|
83
|
+
index = Extracted(tables=plan.extracted())
|
|
84
|
+
(directory / "index.json").write_text(index.model_dump_json(indent=2), "utf-8")
|
|
85
|
+
return ExtractResult(
|
|
86
|
+
server_version=VERSION,
|
|
87
|
+
snapshot=INCONSISTENT,
|
|
88
|
+
snapshot_seconds=round(time.monotonic() - self.opened, 3),
|
|
89
|
+
counts=tuple(counts),
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class FilesSource:
|
|
94
|
+
"""A tree on a path Datadouble can read."""
|
|
95
|
+
|
|
96
|
+
def __init__(self, root: Path, *, accept_inconsistent: bool) -> None:
|
|
97
|
+
"""Read the tree at ``root``."""
|
|
98
|
+
self.root = root
|
|
99
|
+
self.accept_inconsistent = accept_inconsistent
|
|
100
|
+
|
|
101
|
+
def server_version(self) -> str:
|
|
102
|
+
"""The adapter's own format version: a directory has no server."""
|
|
103
|
+
return VERSION
|
|
104
|
+
|
|
105
|
+
def namespaces(self) -> tuple[str, ...]:
|
|
106
|
+
"""The outermost namespaces of the catalog's tables."""
|
|
107
|
+
return outermost(self.catalog())
|
|
108
|
+
|
|
109
|
+
def catalog(self) -> Catalog:
|
|
110
|
+
"""The top-level directories."""
|
|
111
|
+
return catalog(self.root)
|
|
112
|
+
|
|
113
|
+
@contextmanager
|
|
114
|
+
def snapshot(self, as_of: dt.datetime) -> Generator[Snapshot]:
|
|
115
|
+
"""Reads of the live tree, if the spec accepts an inconsistent copy."""
|
|
116
|
+
if not self.accept_inconsistent:
|
|
117
|
+
message = (
|
|
118
|
+
"a consistent copy of a file tree needs a filesystem snapshot, which this"
|
|
119
|
+
" version does not take; set `accept_inconsistent: true` in the files"
|
|
120
|
+
" connection to copy each file as it is when read"
|
|
121
|
+
)
|
|
122
|
+
raise EngineError(message)
|
|
123
|
+
yield FilesSnapshot(self.root, as_of)
|
datadouble_files/tree.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""A file tree as tables: the catalog, and the files a condition chooses.
|
|
5
|
+
|
|
6
|
+
Each top-level directory is a table in the ``files`` namespace. Its rows are
|
|
7
|
+
the regular files under it, keyed by ``path``, the file's path from the
|
|
8
|
+
tree's root (``documents/42/lease.pdf``). Seeds and assertions are ``find``
|
|
9
|
+
tests, run with GNU find on the directory: ``-mtime -30 -size -10M``. Tests
|
|
10
|
+
that act (``-exec``, ``-delete``, the printing ones) or follow symbolic links
|
|
11
|
+
are refused, and only regular files are ever chosen, so nothing outside the
|
|
12
|
+
tree is read.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import datetime as dt
|
|
16
|
+
import os
|
|
17
|
+
import shlex
|
|
18
|
+
from collections.abc import Iterable, Iterator
|
|
19
|
+
from pathlib import Path, PurePosixPath
|
|
20
|
+
from typing import assert_never
|
|
21
|
+
|
|
22
|
+
from datadouble.catalog import Catalog, Column, ColumnKind, Table
|
|
23
|
+
from datadouble.engine import EngineError
|
|
24
|
+
from datadouble.names import ColumnName, EngineName, TableName
|
|
25
|
+
from datadouble.programs import locate, run_program
|
|
26
|
+
from datadouble.subset import (
|
|
27
|
+
AllOf,
|
|
28
|
+
AllRows,
|
|
29
|
+
AnyNull,
|
|
30
|
+
AnyOf,
|
|
31
|
+
Condition,
|
|
32
|
+
NoRows,
|
|
33
|
+
Predicate,
|
|
34
|
+
SelectedBy,
|
|
35
|
+
ValuesIn,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
ENGINE = EngineName("files")
|
|
39
|
+
AS_OF = ":as_of"
|
|
40
|
+
NAMESPACE = "files"
|
|
41
|
+
PATH = ColumnName("path")
|
|
42
|
+
CONTENT = ColumnName("content")
|
|
43
|
+
_REFUSED = frozenset(
|
|
44
|
+
{
|
|
45
|
+
"-exec",
|
|
46
|
+
"-execdir",
|
|
47
|
+
"-ok",
|
|
48
|
+
"-okdir",
|
|
49
|
+
"-delete",
|
|
50
|
+
"-fls",
|
|
51
|
+
"-fprint",
|
|
52
|
+
"-fprint0",
|
|
53
|
+
"-fprintf",
|
|
54
|
+
"-ls",
|
|
55
|
+
"-print",
|
|
56
|
+
"-print0",
|
|
57
|
+
"-printf",
|
|
58
|
+
"-quit",
|
|
59
|
+
"-follow",
|
|
60
|
+
"-files0-from",
|
|
61
|
+
}
|
|
62
|
+
)
|
|
63
|
+
_COLUMNS = (
|
|
64
|
+
Column(name=PATH, type="path", kind=ColumnKind.TEXT, nullable=False),
|
|
65
|
+
Column(name=ColumnName("size"), type="bytes", kind=ColumnKind.INTEGER, nullable=False),
|
|
66
|
+
Column(name=CONTENT, type="bytes", kind=ColumnKind.TEXT, nullable=False),
|
|
67
|
+
)
|
|
68
|
+
"""Every table's columns: ``content`` is what the PII scan reads, the text in each file."""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def table_name(directory: str) -> TableName:
|
|
72
|
+
"""The table of a top-level directory."""
|
|
73
|
+
return TableName.of(NAMESPACE, directory)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def catalog(root: Path) -> Catalog:
|
|
77
|
+
"""One table per top-level directory; fails if the root holds files of its own."""
|
|
78
|
+
if not root.is_dir():
|
|
79
|
+
message = f"the files root {root} is not a directory"
|
|
80
|
+
raise EngineError(message)
|
|
81
|
+
entries = sorted(os.scandir(root), key=lambda entry: entry.name)
|
|
82
|
+
loose = [entry.name for entry in entries if not entry.is_dir(follow_symlinks=False)]
|
|
83
|
+
if loose:
|
|
84
|
+
message = (
|
|
85
|
+
f"the files root holds {len(loose)} entries that are not directories; every file"
|
|
86
|
+
" must be in a top-level directory, which is its table"
|
|
87
|
+
)
|
|
88
|
+
raise EngineError(message)
|
|
89
|
+
tables = tuple(
|
|
90
|
+
Table(name=table_name(entry.name), columns=_COLUMNS, primary_key=(PATH,))
|
|
91
|
+
for entry in entries
|
|
92
|
+
)
|
|
93
|
+
return Catalog(engine=ENGINE, tables=tables)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def find_tests(text: str, as_of: dt.datetime) -> list[str]:
|
|
97
|
+
"""``find`` tests from a seed or assertion; refuses actions and symbolic-link following.
|
|
98
|
+
|
|
99
|
+
The word ``:as_of`` stands for the plan's anchor time, as in ``-newermt :as_of``.
|
|
100
|
+
"""
|
|
101
|
+
try:
|
|
102
|
+
words = [as_of.isoformat() if word == AS_OF else word for word in shlex.split(text)]
|
|
103
|
+
except ValueError as error:
|
|
104
|
+
message = f"cannot read the find tests {text!r}: {error}"
|
|
105
|
+
raise EngineError(message) from None
|
|
106
|
+
refused = sorted({word for word in words if word in _REFUSED})
|
|
107
|
+
if refused:
|
|
108
|
+
message = f"find tests may only test files; {', '.join(refused)} is not allowed"
|
|
109
|
+
raise EngineError(message)
|
|
110
|
+
return words
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def find(directory: Path, words: list[str]) -> set[str]:
|
|
114
|
+
"""The regular files under ``directory`` the tests choose, relative to it."""
|
|
115
|
+
program = locate("find", "DATADOUBLE_FIND")
|
|
116
|
+
if program is None:
|
|
117
|
+
message = "GNU find was not found"
|
|
118
|
+
raise EngineError(message)
|
|
119
|
+
chosen = ["(", *words, ")"] if words else []
|
|
120
|
+
done = run_program(
|
|
121
|
+
program, [str(directory), "-mindepth", "1", *chosen, "-type", "f", "-printf", "%P\\0"]
|
|
122
|
+
)
|
|
123
|
+
if done.status != 0:
|
|
124
|
+
detail = done.stderr.strip().splitlines()[-1:] or [f"status {done.status}"]
|
|
125
|
+
message = f"find failed: {detail[0]}"
|
|
126
|
+
raise EngineError(message)
|
|
127
|
+
return {path for path in done.stdout.split("\0") if path}
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def relative(path: str) -> PurePosixPath | None:
|
|
131
|
+
"""A path from ``paths_from`` as a path in the tree, or None if it leaves the tree."""
|
|
132
|
+
parts = PurePosixPath(path.lstrip("/")).parts
|
|
133
|
+
if not parts or any(part in {"..", ""} for part in parts):
|
|
134
|
+
return None
|
|
135
|
+
return PurePosixPath(*(part for part in parts if part != "."))
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def chosen(root: Path, table: TableName, condition: Condition, as_of: dt.datetime) -> set[str]:
|
|
139
|
+
"""The paths, from the root, of the files in ``table`` the condition chooses."""
|
|
140
|
+
directory = root / table.name
|
|
141
|
+
match condition:
|
|
142
|
+
case AllRows():
|
|
143
|
+
return {f"{table.name}/{path}" for path in find(directory, [])}
|
|
144
|
+
case NoRows() | AnyNull():
|
|
145
|
+
# Every file has a path: none is null.
|
|
146
|
+
return set()
|
|
147
|
+
case Predicate(text):
|
|
148
|
+
return {f"{table.name}/{path}" for path in find(directory, find_tests(text, as_of))}
|
|
149
|
+
case ValuesIn(columns, values):
|
|
150
|
+
if columns != (PATH,):
|
|
151
|
+
message = f"files are chosen by path, not {', '.join(columns)}"
|
|
152
|
+
raise EngineError(message)
|
|
153
|
+
return _listed(root, table, (str(row[0]) for row in values))
|
|
154
|
+
case AnyOf(parts) | AllOf(parts):
|
|
155
|
+
sets = [chosen(root, table, part, as_of) for part in parts]
|
|
156
|
+
if not sets:
|
|
157
|
+
return set()
|
|
158
|
+
first, *rest = sets
|
|
159
|
+
return first.union(*rest) if isinstance(condition, AnyOf) else first.intersection(*rest)
|
|
160
|
+
case SelectedBy():
|
|
161
|
+
message = "file trees have no references; use the keys strategy"
|
|
162
|
+
raise EngineError(message)
|
|
163
|
+
case _:
|
|
164
|
+
assert_never(condition)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _listed(root: Path, table: TableName, paths: Iterable[str]) -> set[str]:
|
|
168
|
+
"""The listed paths that are regular files in ``table``; others are skipped."""
|
|
169
|
+
found: set[str] = set()
|
|
170
|
+
for path in paths:
|
|
171
|
+
inside = relative(path)
|
|
172
|
+
if inside is None or inside.parts[0] != table.name:
|
|
173
|
+
continue
|
|
174
|
+
file = root / inside
|
|
175
|
+
if file.is_file() and not file.is_symlink():
|
|
176
|
+
found.add(str(inside))
|
|
177
|
+
return found
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def files_in(root: Path) -> Iterator[tuple[str, Path]]:
|
|
181
|
+
"""Every regular file under ``root``, with its path from the root."""
|
|
182
|
+
for directory, _, names in os.walk(root):
|
|
183
|
+
for name in sorted(names):
|
|
184
|
+
file = Path(directory) / name
|
|
185
|
+
if file.is_file() and not file.is_symlink():
|
|
186
|
+
yield str(file.relative_to(root)), file
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""The scratch side: working copies, cleanup, images and restores.
|
|
5
|
+
|
|
6
|
+
A working copy is the group's directories from the extract. ``transform``
|
|
7
|
+
copies it and runs the cleanup commands (``after_transform`` hooks) in the
|
|
8
|
+
copy's root, in a container from the files' image, so an interrupted
|
|
9
|
+
transform leaves the loaded copy untouched; column rules do not apply to
|
|
10
|
+
files. The image is the tree itself (``physical``).
|
|
11
|
+
|
|
12
|
+
Verification reads the copy as text: ``content`` yields every run of
|
|
13
|
+
printable characters in each file, which finds personal data in text files
|
|
14
|
+
and in the metadata binary files carry, such as a photo's EXIF fields.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import datetime as dt
|
|
18
|
+
import re
|
|
19
|
+
import shlex
|
|
20
|
+
from collections import Counter
|
|
21
|
+
from collections.abc import Generator, Iterable, Iterator
|
|
22
|
+
from contextlib import contextmanager
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
|
|
25
|
+
from datadouble.catalog import Requirement
|
|
26
|
+
from datadouble.engine import EngineError, RestoredImage, TableCount, Transformation, one_extract
|
|
27
|
+
from datadouble.files import copy_tree
|
|
28
|
+
from datadouble.names import ColumnRef, TableName
|
|
29
|
+
from datadouble.planner import Plan, PlannedGroup
|
|
30
|
+
from datadouble.runtime import Container, ContainerRuntime
|
|
31
|
+
from datadouble.spec import Hook, ImageFormat, TransformHook
|
|
32
|
+
from datadouble.subset import Edge
|
|
33
|
+
from datadouble_files.source import TREE, VERSION, Extracted
|
|
34
|
+
from datadouble_files.tree import CONTENT, PATH, files_in, find, find_tests
|
|
35
|
+
|
|
36
|
+
DEFAULT_IMAGE = (
|
|
37
|
+
"debian:trixie-slim@sha256:a72b4433de1cf7d6bae0c4cee74d0547f58601a643b3375f070c51600d63b6b2"
|
|
38
|
+
)
|
|
39
|
+
"""The image cleanup commands run in when the spec names none."""
|
|
40
|
+
_PRINTABLE = re.compile(rb"[\x20-\x7e]{6,}")
|
|
41
|
+
_EPOCH = dt.datetime(1970, 1, 1, tzinfo=dt.UTC)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _copy(source: Path, destination: Path) -> None:
|
|
45
|
+
problem = copy_tree(source, destination)
|
|
46
|
+
if problem:
|
|
47
|
+
message = f"cannot copy {source.name}: {problem}"
|
|
48
|
+
raise EngineError(message)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _counts(tree: Path, tables: Iterable[TableName]) -> tuple[TableCount, ...]:
|
|
52
|
+
found = Counter(path.split("/", 1)[0] for path, _ in files_in(tree))
|
|
53
|
+
return tuple(TableCount(table=table, rows=found[table.name]) for table in tables)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def text_runs(file: Path) -> Iterator[str]:
|
|
57
|
+
"""The runs of six or more printable ASCII characters in a file."""
|
|
58
|
+
for run in _PRINTABLE.findall(file.read_bytes()):
|
|
59
|
+
yield run.decode("ascii")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class FilesRestored:
|
|
63
|
+
"""A tree open for checks: a restored image, or a working copy."""
|
|
64
|
+
|
|
65
|
+
def __init__(self, tree: Path) -> None:
|
|
66
|
+
"""Check the tree at ``tree``."""
|
|
67
|
+
self.tree = tree
|
|
68
|
+
|
|
69
|
+
def counts(self, tables: Iterable[TableName]) -> dict[TableName, int]:
|
|
70
|
+
"""Files per top-level directory."""
|
|
71
|
+
return {count.table: count.rows for count in _counts(self.tree, tables)}
|
|
72
|
+
|
|
73
|
+
def orphans(self, edge: Edge) -> int:
|
|
74
|
+
"""File trees have no references to check."""
|
|
75
|
+
message = f"{edge.name}: file trees have no references"
|
|
76
|
+
raise EngineError(message)
|
|
77
|
+
|
|
78
|
+
def text_values(self, column: ColumnRef) -> Iterator[str]:
|
|
79
|
+
"""The paths, or the text in the files, of one top-level directory."""
|
|
80
|
+
directory = self.tree / column.table.name
|
|
81
|
+
for path, file in files_in(directory):
|
|
82
|
+
if column.column == PATH:
|
|
83
|
+
yield f"{column.table.name}/{path}"
|
|
84
|
+
elif column.column == CONTENT:
|
|
85
|
+
yield from text_runs(file)
|
|
86
|
+
|
|
87
|
+
def failing_rows(self, query: str) -> int:
|
|
88
|
+
"""Files the find tests in ``query`` choose anywhere in the tree."""
|
|
89
|
+
return len(find(self.tree, find_tests(query, _EPOCH)))
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class FilesWorking:
|
|
93
|
+
"""Working copies and images under one scratch directory."""
|
|
94
|
+
|
|
95
|
+
def __init__(self, runtime: ContainerRuntime, image: str, scratch: Path) -> None:
|
|
96
|
+
"""Run cleanup commands with ``runtime`` in ``image``."""
|
|
97
|
+
self.runtime = runtime
|
|
98
|
+
self.image = image
|
|
99
|
+
self.scratch = scratch
|
|
100
|
+
|
|
101
|
+
def server_version(self) -> str:
|
|
102
|
+
"""The tree layout's version; there is no server."""
|
|
103
|
+
return VERSION
|
|
104
|
+
|
|
105
|
+
def close(self) -> None:
|
|
106
|
+
"""Nothing to stop: it runs no servers."""
|
|
107
|
+
|
|
108
|
+
def available(self) -> tuple[Requirement, ...]:
|
|
109
|
+
"""Nothing yet: this adapter reports no requirements of its sources."""
|
|
110
|
+
return ()
|
|
111
|
+
|
|
112
|
+
def _commands(self, commands: Iterable[str], tree: Path, owner: Path) -> None:
|
|
113
|
+
for number, command in enumerate(commands, 1):
|
|
114
|
+
script = f"cd {shlex.quote(str(tree))} && {command}"
|
|
115
|
+
container = Container(
|
|
116
|
+
image=self.image, command=("sh", "-c", script), owner=owner, mounts=(tree,)
|
|
117
|
+
)
|
|
118
|
+
done = self.runtime.run(container)
|
|
119
|
+
if done.status != 0:
|
|
120
|
+
# The output can name files, which can hold personal data.
|
|
121
|
+
message = f"cleanup command {number} failed with status {done.status}"
|
|
122
|
+
raise EngineError(message)
|
|
123
|
+
|
|
124
|
+
def load(
|
|
125
|
+
self,
|
|
126
|
+
plan: Plan, # noqa: ARG002 - the protocol passes the plan; copying needs only the group
|
|
127
|
+
group: PlannedGroup,
|
|
128
|
+
extracts: tuple[Path, ...],
|
|
129
|
+
directory: Path,
|
|
130
|
+
hooks: tuple[Hook, ...],
|
|
131
|
+
) -> tuple[TableCount, ...]:
|
|
132
|
+
"""Copy the group's directories from the extract; run ``before_load`` commands."""
|
|
133
|
+
extract = one_extract(extracts)
|
|
134
|
+
Extracted.model_validate_json((extract / "index.json").read_bytes())
|
|
135
|
+
tree = directory / TREE
|
|
136
|
+
tree.mkdir(parents=True)
|
|
137
|
+
for table in group.tables:
|
|
138
|
+
if (extract / TREE / table.name).is_dir():
|
|
139
|
+
_copy(extract / TREE / table.name, tree / table.name)
|
|
140
|
+
self._commands((hook.sql for hook in hooks), tree, directory)
|
|
141
|
+
return _counts(tree, group.tables)
|
|
142
|
+
|
|
143
|
+
def transform(
|
|
144
|
+
self,
|
|
145
|
+
group: PlannedGroup,
|
|
146
|
+
source: Path,
|
|
147
|
+
directory: Path,
|
|
148
|
+
transformation: Transformation,
|
|
149
|
+
) -> tuple[TableCount, ...]:
|
|
150
|
+
"""Copy the working copy and run the cleanup commands in the copy."""
|
|
151
|
+
if transformation.rules:
|
|
152
|
+
message = "files take no column rules; clean them with `cleanup` commands"
|
|
153
|
+
raise EngineError(message)
|
|
154
|
+
directory.parent.mkdir(parents=True, exist_ok=True)
|
|
155
|
+
_copy(source, directory)
|
|
156
|
+
tree = directory / TREE
|
|
157
|
+
hooks: tuple[TransformHook, ...] = transformation.hooks
|
|
158
|
+
self._commands((hook.sql for hook in hooks), tree, directory)
|
|
159
|
+
return _counts(tree, group.tables)
|
|
160
|
+
|
|
161
|
+
def package(self, source: Path, image_format: ImageFormat, directory: Path) -> None:
|
|
162
|
+
"""The image is the tree."""
|
|
163
|
+
if image_format is not ImageFormat.PHYSICAL:
|
|
164
|
+
message = "file trees have only physical images"
|
|
165
|
+
raise EngineError(message)
|
|
166
|
+
_copy(source / TREE, directory / TREE)
|
|
167
|
+
|
|
168
|
+
@contextmanager
|
|
169
|
+
def restore(
|
|
170
|
+
self, image: Path, image_format: ImageFormat, directory: Path
|
|
171
|
+
) -> Generator[RestoredImage]:
|
|
172
|
+
"""Copy an image's tree into scratch space for checks."""
|
|
173
|
+
if image_format is not ImageFormat.PHYSICAL:
|
|
174
|
+
message = "file trees have only physical images"
|
|
175
|
+
raise EngineError(message)
|
|
176
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
177
|
+
_copy(image / TREE, directory / TREE)
|
|
178
|
+
yield FilesRestored(directory / TREE)
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: datadouble-files
|
|
3
|
+
Version: 0.0.3
|
|
4
|
+
Summary: File tree engine adapter for Datadouble
|
|
5
|
+
Project-URL: Homepage, https://datadouble.tightlinesoftware.com/
|
|
6
|
+
Project-URL: Source, https://github.com/datadouble/datadouble
|
|
7
|
+
Author: Tight Line LLC
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
11
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
15
|
+
Classifier: Topic :: Database
|
|
16
|
+
Classifier: Typing :: Typed
|
|
17
|
+
Requires-Python: >=3.13
|
|
18
|
+
Requires-Dist: datadouble
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# datadouble-files
|
|
22
|
+
|
|
23
|
+
The file tree engine adapter for [Datadouble](https://datadouble.tightlinesoftware.com/).
|
|
24
|
+
|
|
25
|
+
It copies a spec's `files`: the uploads, documents and other files a
|
|
26
|
+
database's rows refer to, as a second image beside the database's, in the
|
|
27
|
+
same generation and image groups.
|
|
28
|
+
|
|
29
|
+
```yaml
|
|
30
|
+
files:
|
|
31
|
+
connection:
|
|
32
|
+
root: /srv/uploads # the tree, as Datadouble sees it
|
|
33
|
+
accept_inconsistent: true # copy each file as it is when read
|
|
34
|
+
select: # find tests for each top-level directory
|
|
35
|
+
avatars: -mtime -30
|
|
36
|
+
documents: -false # none of its own: only what paths_from names
|
|
37
|
+
exclude: [tmp, cache]
|
|
38
|
+
paths_from: # the files the chosen rows name
|
|
39
|
+
table: customer_documents
|
|
40
|
+
path: '{url}' # a template over the row's columns
|
|
41
|
+
match: '^https://cdn[.]example[.]com/uploads/([^?]+)' # group 1 is the path
|
|
42
|
+
cleanup: # shell, run in the copy's root
|
|
43
|
+
- find . -name '*.log' -delete
|
|
44
|
+
- exiftool -all= -overwrite_original -r ./avatars
|
|
45
|
+
image: vendor/exiftool:13 # the image cleanup runs in; Debian by default
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Each top-level directory is a table whose rows are its regular files, keyed
|
|
49
|
+
by their path from the root. Every top-level directory must be selected or
|
|
50
|
+
excluded, so a new directory fails the plan rather than being copied unseen
|
|
51
|
+
or left out unnoticed. Selection tests are GNU `find` tests; tests that act
|
|
52
|
+
(`-exec`, `-delete`, printing) or follow symbolic links are refused, and only
|
|
53
|
+
regular files are copied. `:as_of` in a test stands for the plan's anchor
|
|
54
|
+
time, as in `-newermt :as_of`.
|
|
55
|
+
|
|
56
|
+
`paths_from` specifies how file paths come from the source's selected rows, by a path
|
|
57
|
+
relative to the root. `path` is a template over a table's columns, such as
|
|
58
|
+
`documents/{customer_id}/{file_name}`, and `match`, if given, a regular
|
|
59
|
+
expression whose first group is the path, for values such as URLs or keys
|
|
60
|
+
with a prefix. `paths_from: customer_documents.path` is short for a column
|
|
61
|
+
that holds the path itself. The values are read inside the source's
|
|
62
|
+
snapshot, and those files are copied too. A path that leaves the tree, or
|
|
63
|
+
names no file, is skipped; values the pattern does not match are counted in
|
|
64
|
+
a warning, since they usually mean the pattern is wrong.
|
|
65
|
+
|
|
66
|
+
Cleanup is not proof: the PII scan reads every copied file's path and the
|
|
67
|
+
runs of printable text in its bytes, which includes a photo's EXIF fields
|
|
68
|
+
and similar metadata, and fails the image if it finds personal data.
|
|
69
|
+
|
|
70
|
+
A consistent copy needs a filesystem snapshot (btrfs, ZFS or LVM), which this
|
|
71
|
+
version does not take, so the extract runs only with `accept_inconsistent:
|
|
72
|
+
true`, and images record that their files were copied as they were when read.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
datadouble_files/__init__.py,sha256=sNjK9BMsumDkE4GlvDRGjOXwLCWLuMEJuXynTP77WHc,3704
|
|
2
|
+
datadouble_files/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
datadouble_files/source.py,sha256=kgwQgKdWjWXXuxJ8FE6wyJQz8boCS9GisZkzGLGpvKc,4817
|
|
4
|
+
datadouble_files/tree.py,sha256=6FTWb-s2qZ0DwwLOrhGN_nvrw5iYR34-cQrbXNqhEgg,6889
|
|
5
|
+
datadouble_files/working.py,sha256=kJsbo4B2oQ0VMaQBdsunCHydJMKX2CM2ARxN4qa4P7E,7309
|
|
6
|
+
datadouble_files-0.0.3.dist-info/METADATA,sha256=zhqV9dhoLayN1Drctho6YwmRkEioM4YckGra5ttWCdg,3463
|
|
7
|
+
datadouble_files-0.0.3.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
datadouble_files-0.0.3.dist-info/entry_points.txt,sha256=CKXK0Z-GIHhZ6hGboRUa2nw5QuEAi_ryGcoN_20ooCw,53
|
|
9
|
+
datadouble_files-0.0.3.dist-info/licenses/LICENSE,sha256=2LcT-SSMiSa7vrHsdC41sUWNmkcwZqIYdYBaSVmqqT8,1072
|
|
10
|
+
datadouble_files-0.0.3.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026- Tight Line LLC
|
|
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.
|