Debian Codegraph @

gavo/base/events.py

raw
1 """
2 General event handling.
3
4 Basically, everything roughly classified as user interaction should go
5 through this module. gavo.base, on import, creates an instance of
6 EventDispatcher and installs it as base.ui. The rest of the library
7 can then call methods of base.ui.
8
9 Clients can then register observers (probably derived from
10 base.observer.Observer) that subscribe to events and can display or
11 log them in some form appropriate to the client.
12 """
13
14 #c Copyright 2008-2025, the GAVO project <[email protected]>
15 #c
16 #c This program is free software, covered by the GNU GPL. See the
17 #c COPYING file in the source distribution.
18
19
20 import contextlib
21 import sys
22
23 from gavo import utils
24
25 from gavo.utils.dachstypes import (Any, BaseEventHandler, Dict,
26 Iterator, List, Optional, SourceToken, Structure, Tuple)
27
28 # the cli sets this to true if exceptions should not be mutated.
29 PDB_ENABLED = False
30
31 class DispatcherType(type):
32 """A metaclass for dispatching of messages.
33
34 Basically, you define methods called notify<whatever> in your class.
35 For each of them, a subscribe<whatever> method is added.
36
37 Then, when notify<whatever> is called, your defined method is called,
38 and its result is then passed to all callbacks passed in through
39 subscribe<whatever>.
40 """
41 def __init__(cls, name: str, bases: Tuple[type, ...], dict: Dict):
42 type.__init__(cls, name, bases, dict)
43 cls.eventTypes: List[str] = []
44 cls._makeNotifiers(dict)
45
46 def _makeNotifier(cls, name: str, callable: BaseEventHandler) -> None:
47 cls.eventTypes.append(name)
48 def notify(self: Any, *args: Any, **kwargs: Any) -> Any:
49 res = callable(self, *args, **kwargs)
50 for callback in self.callbacks[name]:
51 callback(res)
52 return res
53
54 def subscribe(self: Any, callback: BaseEventHandler) -> None:
55 self.subscribe(name, callback)
56
57 def unsubscribe(self: Any, callback: BaseEventHandler) -> None:
58 self.unsubscribe(name, callback)
59
60 setattr(cls, "notify"+name, notify)
61 setattr(cls, "subscribe"+name, subscribe)
62 setattr(cls, "unsubscribe"+name, unsubscribe)
63
64 def _makeNotifiers(cls, dict: Dict[str, BaseEventHandler]):
65 for name, val in dict.items():
66 if name.startswith("notify"):
67 cls._makeNotifier(name[6:], val)
68
69
70 class EventDispatcher(metaclass=DispatcherType):
71 """is the central event dispatcher.
72
73 Events are posted by using notify* methods. Various handlers can
74 then attach to them.
75 """
76
77 def __init__(self) -> None:
78 # mypy 1.0.1 doesn't realise there's an attribute from the metaclass.
79 self.callbacks: Dict[str, List[BaseEventHandler]
80 ] = dict((name, []) for name in self.eventTypes) # type: ignore
81 self.sourceStack: List[Optional[str]] = [None]
82 self.curSource: Optional[str] = None
83
84 # statistics of dachs imp
85 self.totalShippedOut = 0
86 self.totalRead = 0
87 # the last row fed in by a grammar
88 self.lastRow: Optional[Dict[str, Any]] = None
89
90 # the name of a long-running process (if any)
91 self.longRunningProcess: Optional[Structure] = None
92
93 @contextlib.contextmanager
94 def suspended(self, evName: str) -> Iterator[None]:
95 """a context manager suspending notification for a specific event.
96
97 This is mainly for use by test code that wants to avoid spilling
98 too much junk into the log.
99
100 One weak point here is that any subscriptions entered while notification
101 is suspended are lost. So: Don't suspend notifications for normal code.
102 """
103 origCallbacks = self.callbacks[evName]
104 self.callbacks[evName] = []
105 try:
106 yield
107 finally:
108 self.callbacks[evName] = origCallbacks
109
110 def subscribe(self, evName: str, callback: BaseEventHandler) -> None:
111 self.callbacks[evName].append(callback)
112
113 def unsubscribe(self, evName: str, callback: BaseEventHandler) -> None:
114 """removes a callback from evName's callback list.
115
116 It is not an error to unsubscribe a callback that's not subscribed.
117 """
118 try:
119 self.callbacks[evName].remove(callback)
120 except ValueError:
121 pass
122
123 def notifyExceptionMutation(self, newExc: Exception
124 ) -> Tuple[Any, Exception]:
125 """is called when an exception is being handled by raising newExc.
126
127 The callbacks are passed a pair of sys.exc_info() and newExc.
128 """
129 return sys.exc_info(), newExc
130
131 def logOldExc(self, newExc: Exception) -> Exception:
132 """notifies of and ExceptionMutation and returns newExc.
133
134 This is just a convenience when mutating exceptions.
135 """
136 if PDB_ENABLED:
137 # leave original exception for the pdb
138 raise
139 self.notifyExceptionMutation(newExc)
140 return newExc
141
142 def notifyNewSource(self, sourceToken: SourceToken) -> str:
143 """is called when a new source is being operated on.
144
145 The callbacks are passed some, hopefully useful, token string. For
146 file source, this is the file name, otherwise we try to make up
147 something.
148
149 As side effects, the curSource attribute is set to this value.
150 """
151 sourceName = utils.makeSourceEllipsis(sourceToken)
152 self.curSource = sourceName
153 self.sourceStack.append(sourceName)
154 return sourceName
155
156 def notifySourceError(self) -> Optional[str]:
157 """is called when a parse error occurred in a source.
158
159 The callbacks are passed the name of the failing source.
160 """
161 if self.sourceStack: # user-defined grammars may fail to push one
162 lastSource = self.sourceStack.pop()
163 else:
164 lastSource = "Undefined"
165 try:
166 self.curSource = self.sourceStack[-1]
167 except IndexError: # this would be an internal error...
168 self.curSource = None
169 return lastSource
170
171 def notifySourceFinished(self) -> Optional[str]:
172 """is called when a source file has been processed.
173
174 The curSource attribute is updated, and its old value is propagated
175 to the callbacks.
176 """
177 try:
178 lastSource = self.sourceStack.pop()
179 self.curSource = self.sourceStack[-1]
180 except IndexError:
181 # someone didn't notified us of a finish without telling us first
182 # they started. Don't fail because of this.
183 lastSource = None
184 return lastSource
185
186 def notifyShipout(self, numItems: int) -> int:
187 """is called when certain table implementations store items.
188
189 The number of items is passed on to the callbacks. As a side effect,
190 the instance variable totalShippedOut is adjusted.
191
192 InMemoryTables don't call this right now and probably never will.
193 """
194 self.totalShippedOut += numItems
195 return numItems
196
197 def notifyIncomingRow(self, row: Dict[str, Any]) -> Dict[str, Any]:
198 """is called when certain grammars yield a row to the DC's belly.
199
200 The callbacks receive a reference to the row. As a side effect,
201 the instance variable totalRead is bumped up, and lastRow becomes
202 the row passed in.
203
204 To support this, RowIterators have to call this method in their
205 _iterRows. Most will do, DictlistGrammars, e.g., don't.
206 """
207 self.totalRead += 1
208 self.lastRow = row
209 return row
210
211 def notifyIndexCreation(self, indexName: str) -> str:
212 """is called when an index on a DB table is created.
213
214 The callbacks receive the index name.
215 """
216 return indexName
217
218 def notifyScriptRunning(self, script: Structure, source: Structure
219 ) -> Tuple[Structure, Structure]:
220 """is called when a script is being started.
221
222 The callback receives a pair of a scripting.Script and
223 the object the script sits on.
224 """
225 return script, source
226
227 def notifyError(self, errmsg: str) -> str:
228 """is called when something wants to put out an error message.
229
230 The handlers receive the error message as-is.
231
232 In general, you will be in an exception context when you receive
233 this error, but your handlers should not bomb out when you are not.
234 """
235 return errmsg
236
237 def notifyFailure(self, flr: Any, preMsg: str = "") -> None:
238 """is called when an unexpected twisted failure is being processed.
239
240 Call this *exclusively* from errbacks and never while handling
241 an exception, or you'll get two tracebacks in the logs.
242
243 You should not listen on this, since the handler just receives None.
244 Rather, these events are converted to ErrorOccurreds including the
245 failure's traceback.
246 """
247 try:
248 self.notifyError(preMsg
249 +"\n"
250 +str(flr.value))
251 except: # botched str() of exception. Oh my.
252 self.notifyError("Swallowing unstringable exception")
253 # If we're not handling an exception (which is generally true
254 # when we're here because failures typically come up in errbacks),
255 # provide a trace to info, because other handlers can't see it.
256 if sys.exc_info()==(None, None, None):
257 self.notifyInfo("Traceback (nf) a request:\n %s\n%s\n"%(
258 flr.getErrorMessage(), flr.getTraceback()))
259
260 def notifyWarning(self, message: str) -> str:
261 """is called when something tries to emit communicate non-fatal trouble.
262
263 The handlers receive the message as-is
264 """
265 return message
266
267 def notifyInfo(self, message: str) -> str:
268 """is called when something tries to emit auxiliary information.
269
270 The handlers receive the message as-is
271 """
272 return message
273
274 def notifyDebug(self, message: str) -> str:
275 """is called when something wants to communicate information only
276 useful when trying to figure out a malfunction.
277
278 The handlers receive the message as-is.
279 """
280 return message
281
282 def notifyWebServerUp(self) -> None:
283 """is called when the webserver is up and running.
284
285 This passes just a None.
286 """
287 return None
288
289 def notifyDBTableModified(self, fqName: str) -> str:
290 """is called when an existing database table has been modified.
291
292 The argument is the fully qualified table name.
293 """
294 return fqName
295
296 def notifyProcessStarts(self, procDesc: Structure) -> Structure:
297 """is called when a potentially long-running process presumably
298 watched by the user starts.
299
300 There can only be one of those at any time per dachs instance.
301 You have to make sure that notifyProcessEnded is being called.
302 """
303 if self.longRunningProcess is not None:
304 # make this an error although it's a UI thing; if this happens,
305 # it's pretty clear that someone hasn't cleaned up after
306 # themselves, and they need to fix that.
307 raise utils.ReportableError(
308 f"A process was already active ({self.longRunningProcess}).")
309
310 self.longRunningProcess = procDesc
311 return procDesc
312
313 def notifyProcessEnded(self) -> Optional[Structure]:
314 """is called when a potentially long-running process has ended.
315
316 The event handler receives the name of the long running process.
317 """
318 try:
319 return self.longRunningProcess
320 finally:
321 self.longRunningProcess = None
322
323 def notifyProgress(self, progress: str) -> str:
324 """is called to update a progress indicator.
325
326 Progress is a message (like "56%" or so) that is being handed through
327 to the handler.
328 """
329 if not self.longRunningProcess:
330 raise utils.ReportableError("Progress report without process")
331 return progress