Debian Codegraph @

jupyter_cache/executors/base.py

raw
1 from abc import ABC, abstractmethod
2 import logging
3 from typing import Any, Dict, List, Optional, Set
4
5 import attr
6
7 from jupyter_cache.base import JupyterCacheAbstract
8 from jupyter_cache.cache.db import NbProjectRecord
9 from jupyter_cache.entry_points import (
10 ENTRY_POINT_GROUP_EXEC,
11 get_entry_point,
12 list_group_names,
13 )
14
15 base_logger = logging.getLogger(__name__)
16
17
18 class ExecutionError(Exception):
19 pass
20
21
22 @attr.s(slots=True)
23 class ExecutorRunResult:
24 """A container for the execution result."""
25
26 # URIs of notebooks which where successfully executed
27 succeeded: List[str] = attr.ib(factory=list)
28 # URIs of notebooks which excepted during execution
29 excepted: List[str] = attr.ib(factory=list)
30 # URIs of notebooks which errored before execution
31 errored: List[str] = attr.ib(factory=list)
32
33 def all(self) -> List[str]:
34 """Return all notebooks."""
35 return self.succeeded + self.excepted + self.errored
36
37 def as_json(self) -> Dict[str, Any]:
38 """Return the result as a JSON serializable dict."""
39 return {
40 "succeeded": self.succeeded,
41 "excepted": self.excepted,
42 "errored": self.errored,
43 }
44
45
46 class JupyterExecutorAbstract(ABC):
47 """An abstract class for executing notebooks in a cache."""
48
49 def __init__(self, cache: JupyterCacheAbstract, logger=None):
50 self._cache = cache
51 self._logger = logger or logging.getLogger(__name__)
52
53 def __repr__(self):
54 return f"{self.__class__.__name__}(cache={self._cache})"
55
56 @property
57 def cache(self):
58 return self._cache
59
60 @property
61 def logger(self):
62 return self._logger
63
64 def get_records(
65 self,
66 filter_uris: Optional[List[str]] = None,
67 filter_pks: Optional[List[int]] = None,
68 clear_tracebacks: bool = True,
69 force: bool = False,
70 ) -> List[NbProjectRecord]:
71 """Return records to execute.
72
73 :param clear_tracebacks: Remove any tracebacks from previous executions
74 """
75 if force:
76 execute_records = self.cache.list_project_records(filter_uris, filter_pks)
77 else:
78 execute_records = self.cache.list_unexecuted(filter_uris, filter_pks)
79 if clear_tracebacks:
80 NbProjectRecord.remove_tracebacks(
81 [r.pk for r in execute_records], self.cache.db
82 )
83 return execute_records
84
85 @abstractmethod
86 def run_and_cache(
87 self,
88 *,
89 filter_uris: Optional[List[str]] = None,
90 filter_pks: Optional[List[int]] = None,
91 timeout: Optional[int] = 30,
92 allow_errors: bool = False,
93 force: bool = False,
94 **kwargs: Any,
95 ) -> ExecutorRunResult:
96 """Run execution, cache successfully executed notebooks and return their URIs
97
98 :param filter_uris: Filter the notebooks in the project to execute by these URIs
99 :param filter_pks: Filter the notebooks in the project to execute by these PKs
100 :param timeout: Maximum time in seconds to wait for a single cell to run for
101 :param allow_errors: Whether to halt execution on the first cell exception
102 (provided the cell is not tagged as an expected exception)
103 :param force: Whether to force execution of all notebooks, even if they are cached
104 :param kwargs: Additional keyword arguments to pass to the executor
105 """
106
107
108 def list_executors() -> Set[str]:
109 return list_group_names(ENTRY_POINT_GROUP_EXEC)
110
111
112 def load_executor(
113 entry_point: str, cache: JupyterCacheAbstract, logger=None
114 ) -> JupyterExecutorAbstract:
115 """Retrieve an initialised JupyterExecutor from an entry point."""
116 ep = get_entry_point(ENTRY_POINT_GROUP_EXEC, entry_point)
117 if ep is None:
118 raise ImportError(
119 f"Entry point not found: {ENTRY_POINT_GROUP_EXEC}:{entry_point}"
120 )
121 execute_cls = ep.load()
122 return execute_cls(cache=cache, logger=logger)