swindl 3.2.0__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.
swindl/__init__.py ADDED
@@ -0,0 +1,16 @@
1
+ ## begin license ##
2
+ #
3
+ # "Swindl"(Seecr Web Index and Database Lib) combines sjdbl's files and sil's index
4
+ #
5
+ # Copyright (C) 2025-2026 Seecr (Seek You Too B.V.) https://seecr.nl
6
+ #
7
+ # This file is part of "swindl"
8
+ #
9
+ # "swindl" is licensed under the MIT License; see the LICENSE file.
10
+ # SPDX-License-Identifier: MIT
11
+ #
12
+ ## end license ##
13
+
14
+ from ._version import __version__
15
+
16
+ VERSION = __version__.split("+")[0]
swindl/_version.py ADDED
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '3.2.0'
22
+ __version_tuple__ = version_tuple = (3, 2, 0)
23
+
24
+ __commit_id__ = commit_id = 'gf4021d701'
swindl/check.py ADDED
@@ -0,0 +1,207 @@
1
+ ## begin license ##
2
+ #
3
+ # "Swindl"(Seecr Web Index and Database Lib) combines sjdbl's files and sil's index
4
+ #
5
+ # Copyright (C) 2026 Seecr (Seek You Too B.V.) https://seecr.nl
6
+ #
7
+ # This file is part of "swindl"
8
+ #
9
+ # "swindl" is licensed under the MIT License; see the LICENSE file.
10
+ # SPDX-License-Identifier: MIT
11
+ #
12
+ ## end license ##
13
+
14
+ """swindl-check: does the index match the files? Reports, never repairs.
15
+
16
+ swindl-check <data dir> <module>:<list of models>
17
+ swindl-check /data/myapp myapp.models:ALL_MODELS
18
+
19
+ Exit code 0 when all is well, 1 when there are problems (one per line). It only reads:
20
+ it does not open a Store (which would finish an interrupted commit), so it can run
21
+ next to the application, and after a crash it shows what opening the store will do.
22
+ The repair is the application's: open the store (an interrupted commit), or reindex
23
+ (`actions/reindex`) for an index that differs from the files."""
24
+
25
+ import argparse
26
+ import importlib
27
+ import json
28
+ import sys
29
+ from pathlib import Path
30
+
31
+ import tantivy
32
+ from sil.indexfield import INT, UNTOKENIZED, IndexField
33
+ from sjdbl.base import __ARCHIVED__, __ID__, Base, Proxy
34
+
35
+ from .store.indexes import PendingLog
36
+
37
+ ID_FIELD = IndexField.ID_FIELD
38
+
39
+
40
+ class _Files:
41
+ """Reads objects straight from the files (no Store: nothing is changed), and
42
+ remembers the references it saw."""
43
+
44
+ def __init__(self, store_dir, models):
45
+ self._store_dir = store_dir
46
+ self._models = {model.__name__: model for model in models}
47
+ self.referenced = {} # qid -> the qid of an object that refers to it
48
+
49
+ def proxy(self, qid):
50
+ self.referenced.setdefault(qid, self._current)
51
+ return Proxy(self, qid)
52
+
53
+ def get(self, qid):
54
+ cls, _, uuid = qid.partition(":")
55
+ file = self._store_dir / cls / f"{uuid}.json"
56
+ if cls not in self._models or "/" in uuid or not file.is_file():
57
+ return None
58
+ return self._models[cls].from_storage(self, json.loads(file.read_text()))
59
+
60
+ def exists(self, qid):
61
+ cls, _, uuid = qid.partition(":")
62
+ return "/" not in uuid and (self._store_dir / cls / f"{uuid}.json").is_file()
63
+
64
+ def read_all(self, model, problems):
65
+ for file in sorted((self._store_dir / model.__name__).glob("*.json")):
66
+ self._current = f"{model.__name__}:{file.stem}"
67
+ try:
68
+ yield model.from_storage(self, json.loads(file.read_text()))
69
+ except ValueError as e:
70
+ problems.append(f"{file}: not readable: {e}")
71
+
72
+
73
+ def check(data_dir, models):
74
+ """The problems found, as lines of text; [] when all is well."""
75
+ data_dir = Path(data_dir)
76
+ store_dir, index_dir = data_dir / "store", data_dir / "index"
77
+ models = [m for m in models if isinstance(m, type) and issubclass(m, Base)]
78
+ problems = []
79
+
80
+ if (store_dir / "commit.log").exists():
81
+ problems.append(
82
+ "store/commit.log: a commit was interrupted by a crash; opening the store "
83
+ "finishes it"
84
+ )
85
+ for tmp_file in sorted(store_dir.glob("*/*.tmp")):
86
+ problems.append(
87
+ f"{tmp_file.relative_to(data_dir)}: left by a crash; opening the store "
88
+ "removes it"
89
+ )
90
+ if pending := PendingLog(index_dir / "pending.log").qids():
91
+ problems.append(
92
+ f"index/pending.log: {len(pending)} object(s) not yet (surely) indexed; "
93
+ "opening the store indexes them"
94
+ )
95
+
96
+ files = _Files(store_dir, models)
97
+ for model in models:
98
+ objs = list(files.read_all(model, problems))
99
+ if hasattr(model, "INDEX"):
100
+ problems.extend(_check_index(index_dir / model.__name__, model, objs))
101
+
102
+ for qid, by in sorted(files.referenced.items()):
103
+ if not files.exists(qid):
104
+ problems.append(f"{by}: refers to {qid}, which does not exist")
105
+ return problems
106
+
107
+
108
+ def _check_index(path, model, objs):
109
+ name = model.__name__
110
+ if not (path / "index" / "meta.json").exists():
111
+ return [f"index/{name}: no index; reindex"] if objs else []
112
+ try:
113
+ index = tantivy.Index.open(str(path / "index"))
114
+ except ValueError as e:
115
+ return [f"index/{name}: cannot be opened ({e}); reindex"]
116
+ searcher = index.searcher()
117
+ in_index = {}
118
+ if searcher.num_docs:
119
+ hits = searcher.search(tantivy.Query.all_query(), limit=searcher.num_docs).hits
120
+ for _, address in hits:
121
+ qid = searcher.doc(address).to_dict()[ID_FIELD][0]
122
+ in_index[qid] = in_index.get(qid, 0) + 1
123
+
124
+ problems = []
125
+ in_files = {obj.qid: obj for obj in objs}
126
+ for qid in sorted(set(in_index) - set(in_files)):
127
+ problems.append(f"index/{name}: {qid} is indexed but has no file")
128
+ for qid in sorted(set(in_files) - set(in_index)):
129
+ problems.append(f"index/{name}: {qid} has a file but is not indexed")
130
+ for qid, count in sorted(in_index.items()):
131
+ if count > 1:
132
+ problems.append(f"index/{name}: {qid} is indexed {count} times")
133
+
134
+ exact = [
135
+ field
136
+ for field in [IndexField.untokenized(__ARCHIVED__), *model.INDEX]
137
+ if field.field_type in (UNTOKENIZED, INT) and field.name != ID_FIELD
138
+ ]
139
+ schema = index.schema
140
+ for qid in sorted(set(in_files) & set(in_index)):
141
+ obj = in_files[qid]
142
+ values = obj.index_values()
143
+ values[__ID__] = str(obj[__ID__])
144
+ values[__ARCHIVED__] = str(obj[__ARCHIVED__])
145
+ for field in exact:
146
+ value = values.get(field.name)
147
+ for each in (
148
+ [] if value is None else value if isinstance(value, list) else [value]
149
+ ):
150
+ query = tantivy.Query.boolean_query(
151
+ [
152
+ (
153
+ tantivy.Occur.Must,
154
+ tantivy.Query.term_query(schema, ID_FIELD, qid),
155
+ ),
156
+ (
157
+ tantivy.Occur.Must,
158
+ tantivy.Query.term_query(
159
+ schema, field.name, field.term_value(each)
160
+ ),
161
+ ),
162
+ ]
163
+ )
164
+ if searcher.search(query, limit=1).count == 0:
165
+ problems.append(
166
+ f"index/{name}: {qid} is indexed with another {field.name} "
167
+ f"than its file has ({each!r}); reindex"
168
+ )
169
+ return problems
170
+
171
+
172
+ def load_models(spec):
173
+ module_name, _, attribute = spec.partition(":")
174
+ module = importlib.import_module(module_name)
175
+ return (
176
+ getattr(module, attribute)
177
+ if attribute
178
+ else [
179
+ value
180
+ for value in vars(module).values()
181
+ if isinstance(value, type) and issubclass(value, Base) and value is not Base
182
+ ]
183
+ )
184
+
185
+
186
+ def main(argv=None):
187
+ parser = argparse.ArgumentParser(
188
+ prog="swindl-check",
189
+ description="Reports whether a swindl store's index matches its files. "
190
+ "Changes nothing.",
191
+ )
192
+ parser.add_argument("data_dir", type=Path, help="the directory given to Store")
193
+ parser.add_argument(
194
+ "models", help="<module>:<list of models>, or <module> for all models in it"
195
+ )
196
+ args = parser.parse_args(argv)
197
+ sys.path.insert(0, "")
198
+ problems = check(args.data_dir, load_models(args.models))
199
+ for problem in problems:
200
+ print(problem)
201
+ if not problems:
202
+ print("ok")
203
+ return 1 if problems else 0
204
+
205
+
206
+ if __name__ == "__main__":
207
+ sys.exit(main())
swindl/check_test.py ADDED
@@ -0,0 +1,111 @@
1
+ ## begin license ##
2
+ #
3
+ # "Swindl"(Seecr Web Index and Database Lib) combines sjdbl's files and sil's index
4
+ #
5
+ # Copyright (C) 2026 Seecr (Seek You Too B.V.) https://seecr.nl
6
+ #
7
+ # This file is part of "swindl"
8
+ #
9
+ # "swindl" is licensed under the MIT License; see the LICENSE file.
10
+ # SPDX-License-Identifier: MIT
11
+ #
12
+ ## end license ##
13
+
14
+ import json
15
+
16
+ from sil.indexfield import IndexField
17
+ from sjdbl.field import Field
18
+
19
+ from .check import check, main
20
+ from .store import Base
21
+ from .store.indexes import Commit
22
+ from .store.store import Store
23
+
24
+
25
+ class Shelf(Base):
26
+ FIELDS = Base.FIELDS + [Field.str("name")]
27
+
28
+
29
+ class Book(Base):
30
+ FIELDS = Base.FIELDS + [
31
+ Field.str("title"),
32
+ Field.int("year"),
33
+ Field.reference("shelf"),
34
+ ]
35
+ INDEX = Base.INDEX + [
36
+ IndexField.text("title"),
37
+ IndexField.untokenized("code"),
38
+ IndexField.int("year"),
39
+ ]
40
+
41
+ def index_values(self):
42
+ values = super().index_values()
43
+ values.update(title=self.title, code=self.title.lower(), year=self.year)
44
+ return values
45
+
46
+
47
+ MODELS = [Shelf, Book]
48
+
49
+
50
+ def make(tmp_path):
51
+ store = Store(tmp_path, MODELS, commit=Commit(immediate=True))
52
+ shelf = store.create(Shelf, dict(name="top"))
53
+ books = [
54
+ store.create(Book, dict(title=t, year=y, shelf=shelf))
55
+ for t, y in [("Dune", 1965), ("Emma", 1815)]
56
+ ]
57
+ return store, shelf, books
58
+
59
+
60
+ def test_all_is_well(tmp_path):
61
+ store, _, _ = make(tmp_path)
62
+ store.disconnect()
63
+ assert check(tmp_path, MODELS) == []
64
+
65
+
66
+ def test_index_and_files_differ(tmp_path):
67
+ store, shelf, (dune, emma) = make(tmp_path)
68
+ store.disconnect()
69
+ # behind the store's back: a file gone, a file changed, a new file
70
+ (tmp_path / "store" / "Book" / f"{emma.id}.json").unlink()
71
+ file = tmp_path / "store" / "Book" / f"{dune.id}.json"
72
+ record = json.loads(file.read_text())
73
+ record["data"]["year"] = 1966
74
+ file.write_text(json.dumps(record))
75
+ extra = Book.create(title="New", year=2000)
76
+ (tmp_path / "store" / "Book" / f"{extra.id}.json").write_text(
77
+ json.dumps(extra.to_storage())
78
+ )
79
+ (tmp_path / "store" / "Shelf" / f"{shelf.id}.json").unlink()
80
+
81
+ problems = check(tmp_path, MODELS)
82
+ assert any(f"{emma.qid} is indexed but has no file" in p for p in problems)
83
+ assert any(f"{extra.qid} has a file but is not indexed" in p for p in problems)
84
+ assert any(f"{dune.qid} is indexed with another year" in p for p in problems)
85
+ assert any(f"refers to {shelf.qid}, which does not exist" in p for p in problems)
86
+ assert any(f"{shelf.qid} is indexed but has no file" in p for p in problems)
87
+ assert len(problems) == 5
88
+
89
+
90
+ def test_leftovers_of_a_crash(tmp_path):
91
+ store, _, _ = make(tmp_path)
92
+ store.disconnect()
93
+ (tmp_path / "store" / "commit.log").write_text('{"write": [], "delete": []}')
94
+ (tmp_path / "store" / "Book" / "x.tmp").write_text("{")
95
+ (tmp_path / "index" / "pending.log").write_text("Book:x\n")
96
+ (tmp_path / "store" / "Book" / "broken.json").write_text("{")
97
+ problems = check(tmp_path, MODELS)
98
+ assert [p.split(":")[0] for p in problems] == [
99
+ "store/commit.log",
100
+ "store/Book/x.tmp",
101
+ "index/pending.log",
102
+ f"{tmp_path}/store/Book/broken.json",
103
+ ]
104
+
105
+
106
+ def test_main(tmp_path, capsys):
107
+ store, _, _ = make(tmp_path)
108
+ store.disconnect()
109
+ assert main([str(tmp_path), "swindl.check_test:MODELS"]) == 0
110
+ assert capsys.readouterr().out == "ok\n"
111
+ assert main([str(tmp_path), "swindl.check_test"]) == 0
swindl/oai/__init__.py ADDED
@@ -0,0 +1,34 @@
1
+ ## begin license ##
2
+ #
3
+ # "Swindl"(Seecr Web Index and Database Lib) combines sjdbl's files and sil's index
4
+ #
5
+ # Copyright (C) 2026 Seecr (Seek You Too B.V.) https://seecr.nl
6
+ #
7
+ # This file is part of "swindl"
8
+ #
9
+ # "swindl" is licensed under the MIT License; see the LICENSE file.
10
+ # SPDX-License-Identifier: MIT
11
+ #
12
+ ## end license ##
13
+
14
+ """OAI-PMH for swindl: Oai (the OAI administration of a repository, kept in the
15
+ application's Store), OaiProvider (answers OAI-PMH requests) and OaiDownloader
16
+ (harvests another OAI-PMH repository). See "OAI-PMH" in doc/reference.md."""
17
+
18
+ from .downloader import MODELS as DOWNLOADER_MODELS
19
+ from .downloader import OaiDownloader, OaiDownloadState, Record
20
+ from .provider import OaiProvider, OaiResponse
21
+ from .repository import MODELS, Oai, OaiRecord, OaiRepository
22
+
23
+ __all__ = [
24
+ "DOWNLOADER_MODELS",
25
+ "MODELS",
26
+ "Oai",
27
+ "OaiDownloader",
28
+ "OaiDownloadState",
29
+ "OaiProvider",
30
+ "OaiRecord",
31
+ "OaiRepository",
32
+ "OaiResponse",
33
+ "Record",
34
+ ]