-
Notifications
You must be signed in to change notification settings - Fork 97
/
Copy path_session.py
1872 lines (1535 loc) · 63.8 KB
/
_session.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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
__all__ = ("Session", "Inputs", "Outputs", "ClientData")
import asyncio
import contextlib
import dataclasses
import enum
import functools
import json
import os
import re
import sys
import traceback
import typing
import urllib.parse
import warnings
from abc import ABC, abstractmethod
from pathlib import Path
from typing import (
TYPE_CHECKING,
Any,
AsyncIterable,
Awaitable,
Callable,
Iterable,
Literal,
Optional,
Union,
cast,
overload,
)
from htmltools import TagChild, TagList
from starlette.requests import HTTPConnection, Request
from starlette.responses import HTMLResponse, PlainTextResponse, StreamingResponse
from starlette.types import ASGIApp
from .. import _utils, reactive, render
from .._connection import Connection, ConnectionClosed
from .._deprecated import warn_deprecated
from .._docstring import add_example
from .._fileupload import FileInfo, FileUploadManager
from .._namespaces import Id, Root
from .._typing_extensions import NotRequired, TypedDict
from .._utils import wrap_async
from ..bookmark import BookmarkApp, BookmarkProxy
from ..bookmark._button import BOOKMARK_ID
from ..bookmark._restore_state import RestoreContext
from ..http_staticfiles import FileResponse
from ..input_handler import input_handlers
from ..module import ResolvedId
from ..reactive import Effect_, Value, effect
from ..reactive import flush as reactive_flush
from ..reactive import isolate
from ..reactive._core import lock
from ..reactive._core import on_flushed as reactive_on_flushed
from ..render.renderer import Renderer, RendererT
from ..types import (
Jsonifiable,
SafeException,
SilentCancelOutputException,
SilentException,
SilentOperationInProgressException,
)
from ._utils import RenderedDeps, read_thunk_opt, session_context
if TYPE_CHECKING:
from .._app import App
from ..bookmark import Bookmark
from ..bookmark._serializers import Unserializable
class ConnectionState(enum.Enum):
Start = 0
Running = 1
Closed = 2
class ProtocolError(Exception):
message: str
def __init__(self, message: str = ""):
super(ProtocolError, self).__init__(message)
self.message = message
class SessionWarning(RuntimeWarning):
pass
# By default warnings are shown once; we want to always show them.
warnings.simplefilter("always", SessionWarning)
# This cast is necessary because if the type checker thinks that if
# "tag" isn't in `message`, then it's not a ClientMessage object.
# This will be fixable when TypedDict items can be marked as
# potentially missing, in Python 3.10, with PEP 655.
class ClientMessage(TypedDict):
method: str
class ClientMessageInit(ClientMessage):
data: dict[str, object]
class ClientMessageUpdate(ClientMessage):
data: dict[str, object]
# For messages where "method" is something other than "init" or "update".
class ClientMessageOther(ClientMessage):
args: list[object]
tag: int
# This is the type for the function provided by the user to provide the contents of a
# download. It must be a function that takes no arguments, and returns one of:
# 1. A string, which will be interpreted as a path
# 2. A regular Iterable of bytes or strings (i.e. a generator function)
# 3. An AsyncIterable of bytes or strings (i.e. an async generator function)
#
# (Not currently supported is Awaitable[str], could be added easily enough if needed.)
DownloadHandler = Callable[
[],
Union[str, Iterable[Union[bytes, str]], AsyncIterable[Union[bytes, str]]],
]
DynamicRouteHandler = Callable[[Request], ASGIApp]
@dataclasses.dataclass
class DownloadInfo:
filename: Callable[[], str] | str | None
content_type: Optional[Callable[[], str] | str]
handler: DownloadHandler
encoding: str
class OutBoundMessageQueues:
def __init__(self):
self.values: dict[str, Any] = {}
self.errors: dict[str, Any] = {}
self.input_messages: list[dict[str, Any]] = []
def reset(self) -> None:
self.values.clear()
self.errors.clear()
self.input_messages.clear()
def set_value(self, id: str, value: Any) -> None:
self.values[id] = value
# remove from self.errors
if id in self.errors:
del self.errors[id]
def set_error(self, id: str, error: Any) -> None:
self.errors[id] = error
# remove from self.values
if id in self.values:
del self.values[id]
def add_input_message(self, id: str, message: dict[str, Any]) -> None:
self.input_messages.append({"id": id, "message": message})
# ======================================================================================
# Session abstract base class
# ======================================================================================
class Session(ABC):
"""
Interface definition for Session-like classes, like :class:`AppSession`,
:class:`SessionProxy`, and :class:`~shiny.express.ExpressStubSession`.
"""
ns: ResolvedId
app: App
id: str
input: Inputs
output: Outputs
clientdata: ClientData
# Could be done with a weak ref dict from root to all children. Then we could just
# iterate over all modules and check the `.bookmark_exclude` list of each proxy
# session.
bookmark: Bookmark
user: str | None
groups: list[str] | None
# TODO: not sure these should be directly exposed
_outbound_message_queues: OutBoundMessageQueues
_downloads: dict[str, DownloadInfo]
@abstractmethod
def is_stub_session(self) -> bool:
"""
Returns whether this is a stub session.
In the UI-rendering phase of Shiny Express apps, the session context has a stub
session. This stub session is not a real session; it is there only so that code
which expects a session can run without raising errors.
"""
@add_example("session_close")
@abstractmethod
async def close(self, code: int = 1001) -> None:
"""
Close the session.
"""
@abstractmethod
def _is_hidden(self, name: str) -> bool: ...
@add_example("session_on_ended")
@abstractmethod
def on_ended(
self,
fn: Callable[[], None] | Callable[[], Awaitable[None]],
) -> Callable[[], None]:
"""
Registers a function to be called after the client has disconnected.
Parameters
----------
fn
The function to call.
Returns
-------
:
A function that can be used to cancel the registration.
"""
@abstractmethod
def make_scope(self, id: Id) -> Session: ...
@abstractmethod
def root_scope(self) -> Session: ...
@abstractmethod
def _process_ui(self, ui: TagChild) -> RenderedDeps: ...
@abstractmethod
def send_input_message(self, id: str, message: dict[str, object]) -> None:
"""
Send an input message to the session.
Sends a message to an input on the session's client web page; if the input is
present and bound on the page at the time the message is received, then the
input binding object's ``receiveMessage(el, message)`` method will be called.
This method should generally not be called directly from Shiny apps, but through
friendlier wrapper functions like ``ui.update_text()``.
Parameters
----------
id
An id matching the id of an input to update.
message
The message to send.
"""
@abstractmethod
def _send_insert_ui(
self, selector: str, multiple: bool, where: str, content: RenderedDeps
) -> None: ...
@abstractmethod
def _send_remove_ui(self, selector: str, multiple: bool) -> None: ...
@overload
@abstractmethod
def _send_progress(
self, type: Literal["binding"], message: BindingProgressMessage
) -> None:
pass
@overload
@abstractmethod
def _send_progress(
self, type: Literal["open"], message: OpenProgressMessage
) -> None:
pass
@overload
@abstractmethod
def _send_progress(
self, type: Literal["close"], message: CloseProgressMessage
) -> None:
pass
@overload
@abstractmethod
def _send_progress(
self, type: Literal["update"], message: UpdateProgressMessage
) -> None:
pass
@abstractmethod
def _send_progress(self, type: str, message: object) -> None: ...
@add_example("session_send_custom_message")
@abstractmethod
async def send_custom_message(self, type: str, message: dict[str, object]) -> None:
"""
Send a message to the client.
Parameters
----------
type
The type of message to send.
message
The message to send.
Note
----
Sends messages to the client which can be handled in JavaScript with
``Shiny.addCustomMessageHandler(type, function(message){...})``. Once the
message handler is added, it will be invoked each time ``send_custom_message()``
is called on the server.
"""
@abstractmethod
async def _send_message(self, message: dict[str, object]) -> None: ...
@abstractmethod
def _send_message_sync(self, message: dict[str, object]) -> None:
"""
Same as _send_message, except that if the message isn't too large and the socket
isn't too backed up, then the message may be sent synchronously instead of
having to wait until the current task yields (and potentially much longer than
that, if there is a lot of contention for the main thread).
"""
@add_example("session_on_flush")
@abstractmethod
def on_flush(
self,
fn: Callable[[], None] | Callable[[], Awaitable[None]],
once: bool = True,
) -> Callable[[], None]:
"""
Register a function to call before the next reactive flush.
Parameters
----------
fn
The function to call.
once
Whether to call the function only once or on every flush.
Returns
-------
:
A function that can be used to cancel the registration.
"""
@add_example("session_on_flushed")
@abstractmethod
def on_flushed(
self,
fn: Callable[[], None] | Callable[[], Awaitable[None]],
once: bool = True,
) -> Callable[[], None]:
"""
Register a function to call after the next reactive flush.
Parameters
----------
fn
The function to call.
once
Whether to call the function only once or on every flush.
Returns
-------
:
A function that can be used to cancel the registration.
"""
@abstractmethod
async def _unhandled_error(self, e: Exception) -> None: ...
@abstractmethod
def download(
self,
id: Optional[str] = None,
filename: Optional[str | Callable[[], str]] = None,
media_type: None | str | Callable[[], str] = None,
encoding: str = "utf-8",
) -> Callable[[DownloadHandler], None]:
"""
Deprecated. Please use :class:`~shiny.render.download` instead.
Parameters
----------
id
The name of the download.
filename
The filename of the download.
media_type
The media type of the download.
encoding
The encoding of the download.
Returns
-------
:
The decorated function.
"""
@add_example("session_dynamic_route")
@abstractmethod
def dynamic_route(self, name: str, handler: DynamicRouteHandler) -> str:
"""
Register a function to call when a dynamically generated, session-specific,
route is requested.
Provides a convenient way to serve-up session-dependent values for other
clients/applications to consume.
Parameters
----------
name
A name for the route (used to determine part of the URL path).
handler
The function to call when a request is made to the route. This function
should take a single argument (a :class:`starlette.requests.Request` object)
and return a :class:`starlette.types.ASGIApp` object.
Returns
-------
:
The URL path for the route.
"""
@abstractmethod
def set_message_handler(
self,
name: str,
handler: (
Callable[..., Jsonifiable] | Callable[..., Awaitable[Jsonifiable]] | None
),
*,
_handler_session: Optional[Session] = None,
) -> str:
"""
Set a client message handler.
Sets a method that can be called by the client via
`Shiny.shinyapp.makeRequest()`. `Shiny.shinyapp.makeRequest()` makes a request
to the server and waits for a response. By using `makeRequest()` (JS) and
`set_message_handler()` (python), you can have a much richer communication
interaction than just using Input values and re-rendering outputs.
For example, `@render.data_frame` can have many cells edited. While it is
possible to set many input values, if `makeRequest()` did not exist, the data
frame would be updated on the first cell update. This would cause the data frame
to be re-rendered, cancelling any pending cell updates. `makeRequest()` allows
for individual cell updates to be sent to the server, processed, and handled by
the existing data frame output.
When the message handler is executed, it will be executed within an isolated
reactive context and the session context that set the message handler.
Parameters
----------
name
The name of the message handler.
handler
The handler function to be called when the client makes a message for the
given name. The handler function should take any number of arguments that
are provided by the client and return a JSON-serializable object.
If the value is `None`, then the handler at `name` will be removed.
_handler_session
For internal use. This is the session which will be used as the session
context when calling the handler.
Returns
-------
:
The key under which the handler is stored (or removed). This value will be
namespaced when used with a session proxy.
"""
@abstractmethod
def _increment_busy_count(self) -> None: ...
@abstractmethod
def _decrement_busy_count(self) -> None: ...
# ======================================================================================
# AppSession
# ======================================================================================
class AppSession(Session):
"""
A class representing a user session.
"""
# ==========================================================================
# Initialization
# ==========================================================================
def __init__(
self, app: App, id: str, conn: Connection, debug: bool = False
) -> None:
self.ns: ResolvedId = Root
self.app: App = app
self.id: str = id
self._conn: Connection = conn
self._debug: bool = debug
self._busy_count: int = 0
self._message_handlers: dict[
str,
tuple[Callable[..., Awaitable[Jsonifiable]], Session],
] = {}
"""
Dictionary of message handlers for the session.
If a request is sent from the client to the server via
`window.Shiny.make_request()`, the server will look up the method in this
dictionary and call the corresponding function with the arguments provided in
the request.
"""
self._init_message_handlers()
# The HTTPConnection representing the WebSocket. This is used so that we can
# query information about the request, like headers, cookies, etc.
self.http_conn: HTTPConnection = conn.get_http_conn()
self.input: Inputs = Inputs(dict())
self.output: Outputs = Outputs(self, self.ns, outputs=dict())
self.clientdata: ClientData = ClientData(self)
self.bookmark: Bookmark = BookmarkApp(self)
self.user: str | None = None
self.groups: list[str] | None = None
credentials_json: str = ""
if "shiny-server-credentials" in self.http_conn.headers:
credentials_json = self.http_conn.headers["shiny-server-credentials"]
elif "rstudio-connect-credentials" in self.http_conn.headers:
# Fall back to "rstudio-connect-credentials" if "shiny-server-credentials"
# isn't available. Note: This is only needed temporarily, because Connect
# treates PyShiny apps as FastAPI apps. When there's proper Shiny support,
# this can be removed.
credentials_json = self.http_conn.headers["rstudio-connect-credentials"]
if credentials_json:
try:
creds = json.loads(credentials_json)
self.user = creds["user"]
self.groups = creds["groups"]
except Exception as e:
print("Error parsing credentials header: " + str(e), file=sys.stderr)
self._outbound_message_queues = OutBoundMessageQueues()
self._file_upload_manager: FileUploadManager = FileUploadManager()
self._on_ended_callbacks = _utils.AsyncCallbacks()
self._has_run_session_ended_tasks: bool = False
self._downloads: dict[str, DownloadInfo] = {}
self._dynamic_routes: dict[str, DynamicRouteHandler] = {}
self._register_session_ended_callbacks()
self._flush_callbacks = _utils.AsyncCallbacks()
self._flushed_callbacks = _utils.AsyncCallbacks()
def _register_session_ended_callbacks(self) -> None:
# This is to be called from the initialization. It registers functions
# that are called when a session ends.
# Clear file upload directories, if present
self.on_ended(self._file_upload_manager.rm_upload_dir)
async def _run_session_ended_tasks(self) -> None:
if self._has_run_session_ended_tasks:
return
self._has_run_session_ended_tasks = True
try:
await self._on_ended_callbacks.invoke()
finally:
self.app._remove_session(self)
def is_stub_session(self) -> Literal[False]:
return False
async def close(self, code: int = 1001) -> None:
await self._conn.close(code, None)
await self._run_session_ended_tasks()
async def _run(self) -> None:
conn_state: ConnectionState = ConnectionState.Start
def verify_state(expected_state: ConnectionState) -> None:
if conn_state != expected_state:
raise ProtocolError("Invalid method for the current session state")
with contextlib.ExitStack() as stack:
try:
await self._send_message(
{
"config": {
"workerId": "",
"sessionId": self.id,
"user": None,
}
}
)
while True:
message: str = await self._conn.receive()
if self._debug:
print("RECV: " + message, flush=True)
try:
message_obj = json.loads(
message, object_hook=_utils.lists_to_tuples
)
except json.JSONDecodeError:
warnings.warn(
"ERROR: Invalid JSON message", SessionWarning, stacklevel=2
)
return
if "method" not in message_obj:
self._print_error_message(
"Message does not contain 'method'.",
)
return
async with lock():
if message_obj["method"] == "init":
verify_state(ConnectionState.Start)
# BOOKMARKS!
if not isinstance(self.bookmark, BookmarkApp):
raise RuntimeError("`.bookmark` must be a BookmarkApp")
if ".clientdata_url_search" in message_obj["data"]:
self.bookmark._set_restore_context(
await RestoreContext.from_query_string(
message_obj["data"][".clientdata_url_search"],
app=self.app,
)
)
else:
self.bookmark._set_restore_context(RestoreContext())
# When a reactive flush occurs, flush the session's outputs,
# errors, etc. to the client. Note that this is
# `reactive._core.on_flushed`, not `self.on_flushed`.
unreg = reactive_on_flushed(self._flush)
# When the session ends, stop flushing outputs on reactive
# flush.
stack.callback(unreg)
# Set up bookmark callbacks here
self.bookmark._create_effects()
conn_state = ConnectionState.Running
message_obj = typing.cast(ClientMessageInit, message_obj)
self._manage_inputs(message_obj["data"])
with session_context(self):
await self.app.server(self.input, self.output, self)
# TODO: Remove this call to reactive_flush() once https://github.com/posit-dev/py-shiny/issues/1889 is fixed
# Workaround: Any `on_flushed()` calls from bookmark's `on_restored()` will be flushed here
if self.bookmark.store != "disable":
await reactive_flush()
elif message_obj["method"] == "update":
verify_state(ConnectionState.Running)
message_obj = typing.cast(ClientMessageUpdate, message_obj)
self._manage_inputs(message_obj["data"])
elif "tag" in message_obj and "args" in message_obj:
verify_state(ConnectionState.Running)
message_obj = typing.cast(ClientMessageOther, message_obj)
await self._dispatch(message_obj)
else:
raise ProtocolError(
f"Unrecognized method {message_obj['method']}"
)
# Progress messages (of the "{binding: {id: xxx}}"" variety) may
# have queued up at this point; let them drain before we send
# the next message.
# https://github.com/posit-dev/py-shiny/issues/1381
await asyncio.sleep(0)
self._request_flush()
await reactive_flush()
except ConnectionClosed:
...
except Exception as e:
try:
# Starting in Python 3.10 this could be traceback.print_exception(e)
traceback.print_exception(*sys.exc_info())
self._print_error_message(e)
except Exception:
pass
finally:
await self.close()
finally:
await self._run_session_ended_tasks()
def _manage_inputs(self, data: dict[str, object]) -> None:
for key, val in data.items():
keys = key.split(":")
if len(keys) > 2:
raise ValueError(
"Input name+type is not allowed to contain more than one ':' -- "
+ key
)
if len(keys) == 2:
val = input_handlers._process_value(
keys[1], val, ResolvedId(keys[0]), self
)
# The keys[0] value is already a fully namespaced id; make that explicit by
# wrapping it in ResolvedId, otherwise self.input will throw an id
# validation error.
self.input[ResolvedId(keys[0])]._set(val)
self.output._manage_hidden()
def _is_hidden(self, name: str) -> bool:
with isolate():
# The .clientdata_output_{name}_hidden string is already a fully namespaced
# id; make that explicit by wrapping it in ResolvedId, otherwise self.input
# will throw an id validation error.
hidden_value_obj = cast(
Value[bool], self.input[ResolvedId(f".clientdata_output_{name}_hidden")]
)
if not hidden_value_obj.is_set():
return True
return hidden_value_obj()
# ==========================================================================
# Message handlers
# ==========================================================================
async def _dispatch(self, message: ClientMessageOther) -> None:
try:
async_func, handler_session = self._message_handlers[message["method"]]
except KeyError:
await self._send_error_response(
message,
"Unknown method: " + message["method"],
)
return
except AttributeError:
await self._send_error_response(
message,
"Unknown method: " + message["method"],
)
return
try:
# TODO: handle `blobs`
# * Use the session context from when the message handler was set
# * Using `isolate()` allows the handler to read reactive values in a
# non-reactive context
with session_context(handler_session), isolate():
value = await async_func(*message["args"])
except Exception as e:
# Safe error handling!
if self.app.sanitize_errors and not isinstance(e, SafeException):
await self._send_error_response(message, self.app.sanitize_error_msg)
else:
await self._send_error_response(message, str(e))
return
await self._send_response(message, value)
async def _send_response(self, message: ClientMessageOther, value: object) -> None:
await self._send_message({"response": {"tag": message["tag"], "value": value}})
# This is called during __init__.
def _init_message_handlers(self):
# TODO-future; Make sure these methods work within MockSession
async def uploadInit(file_infos: list[FileInfo]) -> dict[str, Jsonifiable]:
with session_context(self):
if self._debug:
print("Upload init: " + str(file_infos), flush=True)
# TODO: Don't alter message in place?
for fi in file_infos:
if fi["type"] == "":
fi["type"] = _utils.guess_mime_type(fi["name"])
job_id = self._file_upload_manager.create_upload_operation(file_infos)
worker_id = ""
return {
"jobId": job_id,
"uploadUrl": f"session/{self.id}/upload/{job_id}?w={worker_id}",
}
async def uploadEnd(job_id: str, input_id: str) -> None:
upload_op = self._file_upload_manager.get_upload_operation(job_id)
if upload_op is None:
warnings.warn(
"Received uploadEnd message for non-existent upload operation.",
SessionWarning,
stacklevel=2,
)
return None
file_data = upload_op.finish()
# The input_id string is already a fully namespaced id; make that explicit
# by wrapping it in ResolvedId, otherwise self.input will throw an id
# validation error.
self.input[ResolvedId(input_id)]._set(file_data)
# Explicitly return None to signal that the message was handled.
return None
self.set_message_handler("uploadInit", uploadInit)
self.set_message_handler("uploadEnd", uploadEnd)
# ==========================================================================
# Handling /session/{session_id}/{action}/{subpath} requests
# ==========================================================================
async def _handle_request(
self, request: Request, action: str, subpath: Optional[str]
) -> ASGIApp:
self._increment_busy_count()
try:
return await self._handle_request_impl(request, action, subpath)
finally:
self._decrement_busy_count()
async def _handle_request_impl(
self, request: Request, action: str, subpath: Optional[str]
) -> ASGIApp:
if action == "upload" and request.method == "POST":
if subpath is None or subpath == "":
return HTMLResponse("<h1>Bad Request</h1>", 400)
job_id = subpath
upload_op = self._file_upload_manager.get_upload_operation(job_id)
if not upload_op:
return HTMLResponse("<h1>Bad Request</h1>", 400)
# The FileUploadOperation can have multiple files; each one will
# have a separate POST request. Each call to `with upload_op` will
# open up each file (in sequence) for writing.
with upload_op:
async for chunk in request.stream():
upload_op.write_chunk(chunk)
return PlainTextResponse("OK", 200)
elif action == "download" and request.method == "GET" and subpath:
download_id = subpath
if download_id in self._downloads:
with session_context(self):
with isolate():
download = self._downloads[download_id]
filename = read_thunk_opt(download.filename)
content_type = read_thunk_opt(download.content_type)
contents = download.handler()
if filename is None:
if isinstance(contents, str):
filename = os.path.basename(contents)
else:
warnings.warn(
"Unable to infer a filename for the "
f"'{download_id}' download handler; please use "
"@render.download(filename=) to specify one "
"manually",
SessionWarning,
stacklevel=2,
)
filename = download_id
if content_type is None:
content_type = _utils.guess_mime_type(filename)
content_disposition_filename = urllib.parse.quote(filename)
if content_disposition_filename != filename:
content_disposition = f"attachment; filename*=utf-8''{content_disposition_filename}"
else:
content_disposition = f'attachment; filename="{filename}"'
headers = {
"Content-Disposition": content_disposition,
"Cache-Control": "no-store",
}
if isinstance(contents, str):
# contents is the path to a file
return FileResponse(
Path(contents),
headers=headers,
media_type=content_type,
)
wrapped_contents: AsyncIterable[bytes]
if isinstance(contents, AsyncIterable):
# Need to wrap the app-author-provided iterator in a
# callback that installs the appropriate context mgrs.
# We already use this context mgrs further up in the
# implementation of handle_request(), but the iterators
# aren't invoked until after handle_request() returns.
async def wrap_content_async() -> AsyncIterable[bytes]:
with session_context(self):
with isolate():
async for chunk in contents:
if isinstance(chunk, str):
yield chunk.encode(download.encoding)
else:
yield chunk
wrapped_contents = wrap_content_async()
else: # isinstance(contents, Iterable):
async def wrap_content_sync() -> AsyncIterable[bytes]:
with session_context(self):
with isolate():
for chunk in contents:
if isinstance(chunk, str):
yield chunk.encode(download.encoding)
else:
yield chunk
wrapped_contents = wrap_content_sync()
# In streaming downloads, we send a 200 response, but if an
# error occurs in the middle of it, the client needs to know.
# With chunked encoding, the client will know if an error occurs
# if it does not receive a terminating (empty) chunk.
headers["Transfer-Encoding"] = "chunked"
return StreamingResponse(
wrapped_contents,
200,
headers=headers,
media_type=content_type, # type: ignore
)
elif action == "dynamic_route" and request.method == "GET" and subpath:
name = subpath
handler = self._dynamic_routes.get(name, None)
if handler is None:
return HTMLResponse("<h1>Bad Request</h1>", 400)
with session_context(self):
with isolate():
if _utils.is_async_callable(handler):
return await handler(request)
else:
return handler(request)
return HTMLResponse("<h1>Not Found</h1>", 404)
def send_input_message(self, id: str, message: dict[str, object]) -> None:
self._outbound_message_queues.add_input_message(id, message)
self._request_flush()
def _send_insert_ui(
self, selector: str, multiple: bool, where: str, content: RenderedDeps
) -> None:
msg = {
"selector": selector,
"multiple": multiple,
"where": where,
"content": content,
}
self._send_message_sync({"shiny-insert-ui": msg})
def _send_remove_ui(self, selector: str, multiple: bool) -> None:
msg = {"selector": selector, "multiple": multiple}
self._send_message_sync({"shiny-remove-ui": msg})
def _send_progress(self, type: str, message: object) -> None:
msg: dict[str, object] = {"progress": {"type": type, "message": message}}
self._send_message_sync(msg)
async def send_custom_message(self, type: str, message: dict[str, object]) -> None:
await self._send_message({"custom": {type: message}})
async def _send_message(self, message: dict[str, object]) -> None:
message_str = json.dumps(message)
if self._debug:
print(
"SEND: "