Debian Codegraph @

jupyter_cache/base.py

raw
1 """This module defines the abstract interface of the cache.
2
3 API access to the cache should use this interface,
4 with no assumptions about the backend storage/retrieval mechanisms.
5 """
6 from abc import ABC, abstractmethod
7 import io
8 from pathlib import Path
9 from typing import Iterable, List, Mapping, Optional, Tuple, Union
10
11 import attr
12 from attr.validators import instance_of, optional
13 import nbformat as nbf
14
15 # TODO make these abstract
16 from jupyter_cache.cache.db import NbCacheRecord, NbProjectRecord
17 from jupyter_cache.readers import DEFAULT_READ_DATA
18
19 NB_VERSION = 4
20
21
22 class CachingError(Exception):
23 """An error to raise when adding to the cache fails."""
24
25
26 class RetrievalError(Exception):
27 """An error to raise when retrieving from the cache fails."""
28
29
30 class NbValidityError(Exception):
31 """Signals a notebook may not be valid to cache.
32
33 For example, because it has not yet been executed.
34 """
35
36 def __init__(self, message, nb_bundle, *args, **kwargs):
37 self.uri = nb_bundle.uri
38 super().__init__(message, *args, **kwargs)
39
40
41 @attr.s(frozen=True, slots=True)
42 class ProjectNb:
43 """A notebook read from a project"""
44
45 pk: int = attr.ib(
46 validator=instance_of(int),
47 metadata={"help": "the ID of the notebook"},
48 )
49 uri: str = attr.ib(
50 converter=str,
51 validator=instance_of(str),
52 metadata={"help": "the URI of the notebook"},
53 )
54 nb: nbf.NotebookNode = attr.ib(
55 validator=instance_of(nbf.NotebookNode),
56 repr=lambda nb: f"Notebook(cells={len(nb.cells)})",
57 metadata={"help": "the notebook"},
58 )
59 assets: List[Path] = attr.ib(
60 factory=list,
61 metadata={"help": "File paths required to run the notebook"},
62 )
63
64
65 class NbArtifactsAbstract(ABC):
66 """Container for artefacts of a notebook execution."""
67
68 @property
69 @abstractmethod
70 def relative_paths(self) -> List[Path]:
71 """Return the list of paths (relative to the notebook folder)."""
72
73 @abstractmethod
74 def __iter__(self) -> Iterable[Tuple[Path, io.BufferedReader]]:
75 """Yield the relative path and open files (in bytes mode)"""
76
77 def __repr__(self):
78 return f"{self.__class__.__name__}(paths={len(self.relative_paths)})"
79
80
81 @attr.s(frozen=True, slots=True)
82 class CacheBundleIn:
83 """A container for notebooks and their associated data to cache."""
84
85 nb: nbf.NotebookNode = attr.ib(
86 validator=instance_of(nbf.NotebookNode),
87 repr=lambda nb: f"Notebook(cells={len(nb.cells)})",
88 metadata={"help": "the notebook"},
89 )
90 uri: str = attr.ib(
91 converter=str,
92 validator=instance_of(str),
93 metadata={"help": "the origin URI of the notebook"},
94 )
95 artifacts: Optional[NbArtifactsAbstract] = attr.ib(
96 kw_only=True,
97 default=None,
98 metadata={"help": "artifacts created during the notebook execution"},
99 )
100 data: dict = attr.ib(
101 kw_only=True,
102 factory=dict,
103 validator=instance_of(dict),
104 metadata={"help": "additional data related to the execution"},
105 )
106 traceback: Optional[str] = attr.ib(
107 kw_only=True,
108 default=None,
109 validator=optional(instance_of(str)),
110 metadata={"help": "the traceback, if the execution excepted"},
111 )
112
113
114 @attr.s(frozen=True, slots=True)
115 class CacheBundleOut:
116 """A container for notebooks and their associated data that have been cached."""
117
118 nb: nbf.NotebookNode = attr.ib(
119 validator=instance_of(nbf.NotebookNode),
120 repr=lambda nb: f"Notebook(cells={len(nb.cells)})",
121 metadata={"help": "the notebook"},
122 )
123 record: NbCacheRecord = attr.ib(metadata={"help": "the cache record"})
124 artifacts: Optional[NbArtifactsAbstract] = attr.ib(
125 default=None,
126 metadata={"help": "artifacts created during the notebook execution"},
127 )
128
129
130 class JupyterCacheAbstract(ABC):
131 """An abstract cache for storing pre/post executed notebooks.
132
133 Note: class instances should be pickleable.
134 """
135
136 @abstractmethod
137 def get_version(self) -> Optional[str]:
138 """Return the version of the cache."""
139
140 @abstractmethod
141 def clear_cache(self) -> None:
142 """Clear the cache completely."""
143
144 @abstractmethod
145 def cache_notebook_bundle(
146 self,
147 bundle: CacheBundleIn,
148 check_validity: bool = True,
149 overwrite: bool = False,
150 ) -> NbCacheRecord:
151 """Commit an executed notebook, returning its cache record.
152
153 Note: non-code source text (e.g. markdown) is not stored in the cache.
154
155 :param bundle: The notebook bundle
156 :param check_validity: check that the notebook has been executed correctly,
157 by asserting `execution_count`s are consecutive and start at 1.
158 :param overwrite: Allow overwrite of cache with matching hash
159 :return: The primary key of the cache
160 """
161
162 @abstractmethod
163 def cache_notebook_file(
164 self,
165 path: str,
166 uri: Optional[str] = None,
167 artifacts: List[str] = (),
168 data: Optional[dict] = None,
169 check_validity: bool = True,
170 overwrite: bool = False,
171 ) -> NbCacheRecord:
172 """Commit an executed notebook, returning its cache record.
173
174 Note: non-code source text (e.g. markdown) is not stored in the cache.
175
176 :param path: path to the notebook
177 :param uri: alternative URI to store in the cache record (defaults to path)
178 :param artifacts: list of paths to outputs of the executed notebook.
179 Artifacts must be in the same folder as the notebook (or a sub-folder)
180 :param data: additional, JSONable, data about the cache
181 :param check_validity: check that the notebook has been executed correctly,
182 by asserting `execution_count`s are consecutive and start at 1.
183 :param overwrite: Allow overwrite of cache with matching hash
184 :return: The primary key of the cache
185 """
186
187 @abstractmethod
188 def list_cache_records(self) -> List[NbCacheRecord]:
189 """Return a list of cached notebook records."""
190
191 @abstractmethod
192 def get_cache_record(self, pk: int) -> NbCacheRecord:
193 """Return the record of a cache, by its primary key"""
194
195 @abstractmethod
196 def get_cache_bundle(self, pk: int) -> CacheBundleOut:
197 """Return an executed notebook bundle, by its primary key"""
198
199 @abstractmethod
200 def cache_artefacts_temppath(self, pk: int) -> Path:
201 """Context manager to provide a temporary folder path to the notebook artifacts.
202
203 Note this path is only guaranteed to exist within the scope of the context,
204 and should only be used for read/copy operations::
205
206 with cache.cache_artefacts_temppath(1) as path:
207 shutil.copytree(path, destination)
208 """
209
210 @abstractmethod
211 def match_cache_notebook(self, nb: nbf.NotebookNode) -> NbCacheRecord:
212 """Match to an executed notebook, returning its primary key.
213
214 :raises KeyError: if no match is found
215 """
216
217 def match_cache_file(self, path: str) -> NbCacheRecord:
218 """Match to an executed notebook, returning its primary key.
219
220 :raises KeyError: if no match is found
221 """
222 notebook = nbf.read(path, nbf.NO_CONVERT)
223 return self.match_cache_notebook(notebook)
224
225 @abstractmethod
226 def merge_match_into_notebook(
227 self,
228 nb: nbf.NotebookNode,
229 nb_meta=("kernelspec", "language_info", "widgets"),
230 cell_meta=None,
231 ) -> Tuple[int, nbf.NotebookNode]:
232 """Match to an executed notebook and return a merged version
233
234 :param nb: The input notebook
235 :param nb_meta: metadata keys to merge from the cache (all if None)
236 :param cell_meta: cell metadata keys to merge from the cache (all if None)
237 :raises KeyError: if no match is found
238 :return: pk, input notebook with cached code cells and metadata merged.
239 """
240
241 def merge_match_into_file(
242 self,
243 path: str,
244 nb_meta=("kernelspec", "language_info", "widgets"),
245 cell_meta=None,
246 ) -> Tuple[int, nbf.NotebookNode]:
247 """Match to an executed notebook and return a merged version
248
249 :param path: The input notebook path
250 :param nb_meta: metadata keys to merge from the cache (all if None)
251 :param cell_meta: cell metadata keys to merge from the cache (all if None)
252 :raises KeyError: if no match is found
253 :return: pk, input notebook with cached code cells and metadata merged.
254 """
255 nb = nbf.read(str(path), nbf.NO_CONVERT)
256 return self.merge_match_into_notebook(nb, nb_meta, cell_meta)
257
258 @abstractmethod
259 def diff_nbnode_with_cache(
260 self, pk: int, nb: nbf.NotebookNode, uri: str = "", as_str=False, **kwargs
261 ) -> Union[str, dict]:
262 """Return a diff of a notebook to a cached one.
263
264 Note: this will not diff markdown content, since it is not stored in the cache.
265 """
266
267 def diff_nbfile_with_cache(
268 self, pk: int, path: str, as_str=False, **kwargs
269 ) -> Union[str, dict]:
270 """Return a diff of a notebook to a cached one.
271
272 Note: this will not diff markdown content, since it is not stored in the cache.
273 """
274 nb = nbf.read(path, nbf.NO_CONVERT)
275 return self.diff_nbnode_with_cache(pk, nb, uri=path, as_str=as_str, **kwargs)
276
277 @abstractmethod
278 def add_nb_to_project(
279 self,
280 uri: str,
281 *,
282 read_data: Mapping = DEFAULT_READ_DATA,
283 assets: List[str] = (),
284 ) -> NbProjectRecord:
285 """Add a single notebook to the project.
286
287 :param uri: The path to the file
288 :param read_data: Data to generate a function, to read the uri and return a NotebookNode
289 :param assets: The path of files required by the notebook to run.
290 :raises ValueError: assets not within the same folder as the notebook URI.
291 """
292
293 @abstractmethod
294 def remove_nb_from_project(self, uri_or_pk: Union[int, str]):
295 """Remove a notebook from the project."""
296
297 @abstractmethod
298 def list_project_records(
299 self,
300 filter_uris: Optional[List[str]] = None,
301 filter_pks: Optional[List[int]] = None,
302 ) -> List[NbProjectRecord]:
303 """Return a list of all notebook records in the project."""
304
305 @abstractmethod
306 def get_project_record(self, uri_or_pk: Union[int, str]) -> NbProjectRecord:
307 """Return the record of a notebook in the project, by its primary key or URI."""
308
309 @abstractmethod
310 def get_project_notebook(self, uri_or_pk: Union[int, str]) -> ProjectNb:
311 """Return a single notebook in the project, by its primary key or URI.
312
313 :raises NbReadError: if the notebook cannot be read
314 """
315
316 @abstractmethod
317 def get_cached_project_nb(
318 self, uri_or_pk: Union[int, str]
319 ) -> Optional[NbCacheRecord]:
320 """Get cache record for a notebook in the project.
321
322 :param uri_or_pk: The URI of pk of the file in the project
323 """
324
325 @abstractmethod
326 def list_unexecuted(
327 self,
328 filter_uris: Optional[List[str]] = None,
329 filter_pks: Optional[List[int]] = None,
330 ) -> List[NbProjectRecord]:
331 """List notebooks in the project, whose hash is not present in the cache."""