-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Expand file tree
/
Copy pathmetastore.py
More file actions
243 lines (185 loc) · 7.19 KB
/
metastore.py
File metadata and controls
243 lines (185 loc) · 7.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
"""Interfaces for accessing metadata.
We provide two implementations.
* The "classic" file system implementation, which uses a directory
structure of files.
* A hokey sqlite backed implementation, which basically simulates
the file system in an effort to work around poor file system performance
on OS X.
"""
from __future__ import annotations
import binascii
import os
import time
from abc import abstractmethod
from collections.abc import Iterable
from typing import TYPE_CHECKING, Any
from mypy.util import os_path_join
if TYPE_CHECKING:
# We avoid importing sqlite3 unless we are using it so we can mostly work
# on semi-broken pythons that are missing it.
import sqlite3
class MetadataStore:
"""Generic interface for metadata storage."""
@abstractmethod
def getmtime(self, name: str) -> float:
"""Read the mtime of a metadata entry.
Raises FileNotFound if the entry does not exist.
"""
@abstractmethod
def read(self, name: str) -> bytes:
"""Read the contents of a metadata entry.
Raises FileNotFound if the entry does not exist.
"""
@abstractmethod
def write(self, name: str, data: bytes, mtime: float | None = None) -> bool:
"""Write a metadata entry.
If mtime is specified, set it as the mtime of the entry. Otherwise,
the current time is used.
Returns True if the entry is successfully written, False otherwise.
"""
@abstractmethod
def remove(self, name: str) -> None:
"""Delete a metadata entry"""
@abstractmethod
def commit(self) -> None:
"""If the backing store requires a commit, do it.
But N.B. that this is not *guaranteed* to do anything, and
there is no guarantee that changes are not made until it is
called.
"""
@abstractmethod
def list_all(self) -> Iterable[str]: ...
@abstractmethod
def close(self) -> None:
"""Release any resources held by the backing store."""
def random_string() -> str:
return binascii.hexlify(os.urandom(8)).decode("ascii")
class FilesystemMetadataStore(MetadataStore):
def __init__(self, cache_dir_prefix: str) -> None:
# We check startswith instead of equality because the version
# will have already been appended by the time the cache dir is
# passed here.
if cache_dir_prefix.startswith(os.devnull):
self.cache_dir_prefix = None
else:
self.cache_dir_prefix = cache_dir_prefix
def getmtime(self, name: str) -> float:
if not self.cache_dir_prefix:
raise FileNotFoundError()
return int(os.path.getmtime(os_path_join(self.cache_dir_prefix, name)))
def read(self, name: str) -> bytes:
assert not os.path.isabs(name), "Don't use absolute paths!"
if not self.cache_dir_prefix:
raise FileNotFoundError()
with open(os_path_join(self.cache_dir_prefix, name), "rb", buffering=0) as f:
return f.read()
def write(self, name: str, data: bytes, mtime: float | None = None) -> bool:
assert not os.path.isabs(name), "Don't use absolute paths!"
if not self.cache_dir_prefix:
return False
path = os_path_join(self.cache_dir_prefix, name)
tmp_filename = path + "." + random_string()
try:
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(tmp_filename, "wb") as f:
f.write(data)
os.replace(tmp_filename, path)
if mtime is not None:
os.utime(path, times=(mtime, mtime))
except OSError:
return False
return True
def remove(self, name: str) -> None:
if not self.cache_dir_prefix:
raise FileNotFoundError()
os.remove(os_path_join(self.cache_dir_prefix, name))
def commit(self) -> None:
pass
def list_all(self) -> Iterable[str]:
if not self.cache_dir_prefix:
return
for dir, _, files in os.walk(self.cache_dir_prefix):
dir = os.path.relpath(dir, self.cache_dir_prefix)
for file in files:
yield os.path.normpath(os_path_join(dir, file))
def close(self) -> None:
pass
SCHEMA = """
CREATE TABLE IF NOT EXISTS files2 (
path TEXT UNIQUE NOT NULL,
mtime REAL,
data BLOB
);
CREATE INDEX IF NOT EXISTS path_idx on files2(path);
"""
def connect_db(db_file: str, set_journal_mode: bool) -> sqlite3.Connection:
import sqlite3.dbapi2
db = sqlite3.dbapi2.connect(db_file, check_same_thread=False)
# This is a bit unfortunate (as we may get corrupt cache after e.g. Ctrl + C),
# but without this flag, commits are *very* slow, especially when using HDDs,
# see https://www.sqlite.org/faq.html#q19 for details.
db.execute("PRAGMA synchronous=OFF")
if set_journal_mode:
db.execute("PRAGMA journal_mode=WAL")
db.executescript(SCHEMA)
return db
class SqliteMetadataStore(MetadataStore):
def __init__(self, cache_dir_prefix: str, set_journal_mode: bool = False) -> None:
# We check startswith instead of equality because the version
# will have already been appended by the time the cache dir is
# passed here.
self.db = None
if cache_dir_prefix.startswith(os.devnull):
return
os.makedirs(cache_dir_prefix, exist_ok=True)
self.db = connect_db(os_path_join(cache_dir_prefix, "cache.db"), set_journal_mode)
def _query(self, name: str, field: str) -> Any:
# Raises FileNotFound for consistency with the file system version
if not self.db:
raise FileNotFoundError()
cur = self.db.execute(f"SELECT {field} FROM files2 WHERE path = ?", (name,))
results = cur.fetchall()
if not results:
raise FileNotFoundError()
assert len(results) == 1
return results[0][0]
def getmtime(self, name: str) -> float:
mtime = self._query(name, "mtime")
assert isinstance(mtime, float)
return mtime
def read(self, name: str) -> bytes:
data = self._query(name, "data")
assert isinstance(data, bytes)
return data
def write(self, name: str, data: bytes, mtime: float | None = None) -> bool:
import sqlite3
if not self.db:
return False
try:
if mtime is None:
mtime = time.time()
self.db.execute(
"INSERT OR REPLACE INTO files2(path, mtime, data) VALUES(?, ?, ?)",
(name, mtime, data),
)
except sqlite3.OperationalError:
return False
return True
def remove(self, name: str) -> None:
if not self.db:
raise FileNotFoundError()
self.db.execute("DELETE FROM files2 WHERE path = ?", (name,))
def commit(self) -> None:
if self.db:
self.db.commit()
def list_all(self) -> Iterable[str]:
if self.db:
for row in self.db.execute("SELECT path FROM files2"):
yield row[0]
def close(self) -> None:
if self.db:
db = self.db
self.db = None
db.close()
def __del__(self) -> None:
self.close()