-
-
Notifications
You must be signed in to change notification settings - Fork 473
/
document.py
351 lines (303 loc) · 10.6 KB
/
document.py
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
from __future__ import annotations
import asyncio
import dataclasses
import datetime as dt
import inspect
import json
import logging
import threading
from contextlib import contextmanager
from functools import partial, wraps
from typing import (
TYPE_CHECKING, Any, Callable, Dict, Iterator, List, Optional,
)
from bokeh.application.application import SessionContext
from bokeh.document.document import Document
from bokeh.document.events import (
ColumnDataChangedEvent, ColumnsPatchedEvent, ColumnsStreamedEvent,
DocumentChangedEvent, ModelChangedEvent,
)
from bokeh.model.util import visit_immediate_value_references
from bokeh.models import CustomJS
from ..config import config
from ..util import param_watchers
from .loading import LOADING_INDICATOR_CSS_CLASS
from .model import hold, monkeypatch_events # noqa: F401 API import
from .state import curdoc_locked, state
if TYPE_CHECKING:
from bokeh.core.has_props import HasProps
logger = logging.getLogger(__name__)
#---------------------------------------------------------------------
# Private API
#---------------------------------------------------------------------
DISPATCH_EVENTS = (
ColumnDataChangedEvent, ColumnsPatchedEvent, ColumnsStreamedEvent,
ModelChangedEvent
)
@dataclasses.dataclass
class Request:
headers : dict
cookies : dict
arguments : dict
class MockSessionContext(SessionContext):
def __init__(self, *args, document=None, **kwargs):
self._document = document
super().__init__(*args, server_context=None, session_id=None, **kwargs)
def with_locked_document(self, *args):
return
@property
def destroyed(self) -> bool:
return False
@property
def request(self):
return Request(headers={}, cookies={}, arguments={})
def _dispatch_events(doc: Document, events: List[DocumentChangedEvent]) -> None:
"""
Handles dispatch of events which could not be processed in
unlocked decorator.
"""
for event in events:
doc.callbacks.trigger_on_change(event)
def _cleanup_doc(doc, destroy=True):
for callback in doc.session_destroyed_callbacks:
try:
callback(None)
except Exception:
pass
if hasattr(doc.callbacks, '_change_callbacks'):
doc.callbacks._change_callbacks[None] = {}
# Remove views
from ..viewable import Viewable
views = {}
for ref, (pane, root, vdoc, comm) in list(state._views.items()):
if vdoc is doc:
pane._cleanup(root)
if isinstance(pane, Viewable):
pane._hooks = []
for p in pane.select():
p._hooks = []
param_watchers(p, {})
p._documents = {}
p._internal_callbacks = {}
param_watchers(pane, {})
pane._documents = {}
pane._internal_callbacks = {}
else:
views[ref] = (pane, root, doc, comm)
state._views = views
# When reusing sessions we must clean up the Panel state but we
# must **not** destroy the template or the document
if not destroy:
return
# Clean up templates
if doc in state._templates:
tmpl = state._templates[doc]
tmpl._documents = {}
del state._templates[doc]
# Destroy document
doc.destroy(None)
#---------------------------------------------------------------------
# Public API
#---------------------------------------------------------------------
def create_doc_if_none_exists(doc: Optional[Document]) -> Document:
curdoc = doc or curdoc_locked()
if curdoc is None:
curdoc = Document()
elif not isinstance(curdoc, Document):
curdoc = curdoc._doc
return curdoc
def init_doc(doc: Optional[Document]) -> Document:
curdoc = create_doc_if_none_exists(doc)
if not curdoc.session_context:
return curdoc
thread = threading.current_thread()
if thread:
state._thread_id_[curdoc] = thread.ident
if config.global_loading_spinner:
curdoc.js_on_event(
'document_ready', CustomJS(code=f"""
const body = document.getElementsByTagName('body')[0]
body.classList.remove({LOADING_INDICATOR_CSS_CLASS!r}, {config.loading_spinner!r})
""")
)
session_id = curdoc.session_context.id
sessions = state.session_info['sessions']
if session_id not in sessions:
return curdoc
sessions[session_id].update({
'started': dt.datetime.now().timestamp()
})
curdoc.on_event('document_ready', state._init_session)
return curdoc
def with_lock(func: Callable) -> Callable:
"""
Wrap a callback function to execute with a lock allowing the
function to modify bokeh models directly.
Arguments
---------
func: callable
The callable to wrap
Returns
-------
wrapper: callable
Function wrapped to execute without a Document lock.
"""
if inspect.iscoroutinefunction(func):
@wraps(func)
async def wrapper(*args, **kw):
return await func(*args, **kw)
else:
@wraps(func)
def wrapper(*args, **kw):
return func(*args, **kw)
wrapper.lock = True # type: ignore
return wrapper
def dispatch_tornado(conn, events):
from tornado.websocket import WebSocketHandler
socket = conn._socket
ws_conn = getattr(socket, 'ws_connection', False)
if not ws_conn or ws_conn.is_closing(): # type: ignore
return []
msg = conn.protocol.create('PATCH-DOC', events)
futures = [
WebSocketHandler.write_message(socket, msg.header_json),
WebSocketHandler.write_message(socket, msg.metadata_json),
WebSocketHandler.write_message(socket, msg.content_json)
]
for buffer in msg._buffers:
header = json.dumps(buffer.ref)
payload = buffer.to_bytes()
futures.extend([
WebSocketHandler.write_message(socket, header),
WebSocketHandler.write_message(socket, payload, binary=True)
])
return futures
def dispatch_django(conn, events):
socket = conn._socket
msg = conn.protocol.create('PATCH-DOC', events)
futures = [
socket.send(text_data=msg.header_json),
socket.send(text_data=msg.metadata_json),
socket.send(text_data=msg.content_json)
]
for buffer in msg._buffers:
header = json.dumps(buffer.ref)
payload = buffer.to_bytes()
futures.extend([
socket.send(text_data=header),
socket.send(binary_data=payload)
])
return futures
@contextmanager
def unlocked() -> Iterator:
"""
Context manager which unlocks a Document and dispatches
ModelChangedEvents triggered in the context body to all sockets
on current sessions.
"""
curdoc = state.curdoc
session_context = getattr(curdoc, 'session_context', None)
session = getattr(session_context, 'session', None)
if curdoc is None or session_context is None or session is None or state._jupyter_kernel_context:
yield
return
elif curdoc.callbacks.hold_value:
yield
monkeypatch_events(curdoc.callbacks._held_events)
return
from tornado.websocket import WebSocketClosedError, WebSocketHandler
connections = session._subscribed_connections
curdoc.hold()
try:
yield
locked = False
for conn in connections:
socket = conn._socket
if hasattr(socket, 'write_lock') and socket.write_lock._block._value == 0:
locked = True
break
events = curdoc.callbacks._held_events
monkeypatch_events(events)
remaining_events, dispatch_events = [], []
for event in events:
if isinstance(event, DISPATCH_EVENTS) and not locked:
dispatch_events.append(event)
else:
remaining_events.append(event)
futures = []
for conn in connections:
if not dispatch_events:
continue
elif isinstance(conn._socket, WebSocketHandler):
futures += dispatch_tornado(conn, dispatch_events)
else:
futures += dispatch_django(conn, dispatch_events)
# Ensure that all write_message calls are awaited and handled
async def handle_write_errors():
for future in futures:
try:
await future
except WebSocketClosedError:
logger.warning("Failed sending message as connection was closed")
except Exception as e:
logger.warning(f"Failed sending message due to following error: {e}")
if futures:
if state._unblocked(curdoc):
try:
asyncio.ensure_future(handle_write_errors())
except RuntimeError:
curdoc.add_next_tick_callback(handle_write_errors)
else:
curdoc.add_next_tick_callback(handle_write_errors)
curdoc.callbacks._held_events = remaining_events
finally:
try:
curdoc.unhold()
except RuntimeError:
if remaining_events:
curdoc.add_next_tick_callback(partial(_dispatch_events, curdoc, remaining_events))
@contextmanager
def immediate_dispatch(doc: Document | None = None):
"""
Context manager to trigger immediate dispatch of events triggered
inside the execution context even when Document events are
currently on hold.
Arguments
---------
doc: Document
The document to dispatch events on (if `None` then `state.curdoc` is used).
"""
doc = doc or state.curdoc
# Skip if not in a server context
if not doc or not doc._session_context:
yield
return
old_events = doc.callbacks._held_events
held = doc.callbacks._hold
doc.callbacks._held_events = []
doc.callbacks.unhold()
with unlocked():
yield
doc.callbacks._hold = held
doc.callbacks._held_events = old_events
@contextmanager
def freeze_doc(doc: Document, model: HasProps, properties: Dict[str, Any], force: bool = False):
"""
Freezes the document model references if any of the properties
are themselves a model.
"""
if force:
dirty_count = 1
else:
dirty_count = 0
def mark_dirty(_: HasProps):
nonlocal dirty_count
dirty_count += 1
for key, value in properties.items():
visit_immediate_value_references(getattr(model, key, None), mark_dirty)
visit_immediate_value_references(value, mark_dirty)
if dirty_count:
doc.models._push_freeze()
yield
if dirty_count:
doc.models._pop_freeze()