-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathapi.py
More file actions
2231 lines (1902 loc) · 86.7 KB
/
api.py
File metadata and controls
2231 lines (1902 loc) · 86.7 KB
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
"""
Posit Connect API client and utility functions
"""
from __future__ import annotations
import base64
import binascii
import datetime
import hashlib
import hmac
import os
import re
import sys
import time
import typing
import webbrowser
from os.path import abspath, dirname
from ssl import SSLError
from typing import (
IO,
TYPE_CHECKING,
Any,
Callable,
List,
Literal,
Mapping,
Optional,
TypeVar,
Union,
cast,
overload,
)
from urllib import parse
from urllib.parse import urlencode, urlparse
from warnings import warn
import click
if sys.version_info >= (3, 10):
from typing import ParamSpec
else:
from typing_extensions import ParamSpec
# Even though TypedDict is available in Python 3.8, because it's used with NotRequired,
# they should both come from the same typing module.
# https://peps.python.org/pep-0655/#usage-in-python-3-11
if sys.version_info >= (3, 11):
from typing import TypedDict
else:
from typing_extensions import TypedDict
from . import validation
from .bundle import _default_title
from .certificates import read_certificate_file
from .environment import fake_module_file_from_directory
from .exception import DeploymentFailedException, RSConnectException
from .http_support import CookieJar, HTTPResponse, HTTPServer, JsonData, append_to_path
from .log import cls_logged, connect_logger, console_logger, logger
from .metadata import AppStore, ServerStore
from .models import (
AppMode,
AppModes,
AppSearchResults,
BootstrapOutputDTO,
BuildOutputDTO,
ConfigureResult,
ContentItemV0,
ContentItemV1,
DeleteInputDTO,
DeleteOutputDTO,
ListEntryOutputDTO,
PyInfo,
ServerSettings,
TaskStatusV0,
TaskStatusV1,
UserRecord,
)
from .snowflake import generate_jwt, get_parameters
from .timeouts import get_task_timeout, get_task_timeout_help_message
if TYPE_CHECKING:
import logging
T = TypeVar("T")
P = ParamSpec("P")
class AbstractRemoteServer:
def __init__(self, url: str, remote_name: str):
self.url = url
self.remote_name = remote_name
@overload
def handle_bad_response(self, response: HTTPResponse, is_httpresponse: Literal[True]) -> HTTPResponse: ...
@overload
def handle_bad_response(self, response: HTTPResponse | T, is_httpresponse: Literal[False] = False) -> T: ...
def handle_bad_response(self, response: HTTPResponse | T, is_httpresponse: bool = False) -> T | HTTPResponse:
"""
Handle a bad response from the server.
For most requests, we expect the response to already have been converted to
JSON. This is when `is_httpresponse` has the default value False. In these
cases:
* By the time a response object reaches this function, it should have been
converted to the JSON data contained in the original HTTPResponse object.
If the response is still an HTTPResponse object at this point, that means
that something went wrong, and it raises an exception, even if the status
was 2xx.
However, in some cases, we expect that the input object is an HTTPResponse
that did not contain JSON. This is when `is_httpresponse` is set to True. In
these cases:
* The response object should still be an HTTPResponse object. If it has a
2xx status, then it will be returned. If it has any other status, then
an exceptio nwill be raised.
:param response: The response object to check.
:param is_httpresponse: If False (the default), expect that the input object is
a JsonData object. If True, expect that the input object is a HTTPResponse
object.
:return: The response object, if it is not an HTTPResponse object. If it was
an HTTPResponse object, this function will raise an exception and
not return.
"""
if isinstance(response, HTTPResponse):
if response.exception:
raise RSConnectException(
"Exception trying to connect to %s - %s" % (self.url, response.exception), cause=response.exception
)
# Sometimes an ISP will respond to an unknown server name by returning a friendly
# search page so trap that since we know we're expecting JSON from Connect. This
# also catches all error conditions which we will report as "not running Connect".
else:
if (
response.json_data
and isinstance(response.json_data, dict)
and "error" in response.json_data
and response.json_data["error"] is not None
):
error = "%s reported an error (calling %s): %s" % (
self.remote_name,
response.full_uri,
response.json_data["error"],
)
raise RSConnectException(error)
if response.status < 200 or response.status > 299:
raise RSConnectException(
"Received an unexpected response from %s (calling %s): %s %s"
% (
self.remote_name,
response.full_uri,
response.status,
response.reason,
)
)
if not is_httpresponse:
# If we got here, it was a 2xx response that contained JSON and did not
# have an error field, but for some reason the object returned from the
# prior function call was not converted from a HTTPResponse to JSON. This
# should never happen, so raise an exception.
raise RSConnectException(
"Received an unexpected response from %s (calling %s): %s %s"
% (
self.remote_name,
response.full_uri,
response.status,
response.reason,
)
)
return response
class PositServer(AbstractRemoteServer):
"""
A class used to represent the server of the shinyapps.io and Posit Cloud APIs.
"""
def __init__(self, remote_name: str, url: str, account_name: str, token: str, secret: str):
super().__init__(url, remote_name)
self.account_name = account_name
self.token = token
self.secret = secret
class ShinyappsServer(PositServer):
"""
A class to encapsulate the information needed to interact with an
instance of the shinyapps.io server.
"""
def __init__(self, url: str, account_name: str, token: str, secret: str):
remote_name = "shinyapps.io"
if url == "shinyapps.io" or url is None:
url = "https://api.shinyapps.io"
super().__init__(remote_name=remote_name, url=url, account_name=account_name, token=token, secret=secret)
class CloudServer(PositServer):
"""
A class to encapsulate the information needed to interact with an
instance of the Posit Cloud server.
"""
def __init__(self, url: str, account_name: str, token: str, secret: str):
remote_name = "Posit Cloud"
if url in {"posit.cloud", "rstudio.cloud", None}:
url = "https://api.posit.cloud"
super().__init__(remote_name=remote_name, url=url, account_name=account_name, token=token, secret=secret)
class RSConnectServer(AbstractRemoteServer):
"""
A simple class to encapsulate the information needed to interact with an
instance of the Connect server.
"""
def __init__(
self,
url: str,
api_key: Optional[str],
insecure: bool = False,
ca_data: Optional[str | bytes] = None,
bootstrap_jwt: Optional[str] = None,
):
super().__init__(url, "Posit Connect")
self.api_key = api_key
self.bootstrap_jwt = bootstrap_jwt
self.insecure = insecure
self.ca_data = ca_data
# This is specifically not None.
self.cookie_jar = CookieJar()
# for compatibility with RSconnectClient
self.snowflake_connection_name = None
class SPCSConnectServer(AbstractRemoteServer):
"""
A class to encapsulate the information needed to interact with an instance
of Posit Connect deployed in Snowflake SPCS (Snowpark Container Services).
SPCS deployments use Snowflake OIDC authentication combined with Connect API keys.
"""
def __init__(
self,
url: str,
api_key: Optional[str],
snowflake_connection_name: Optional[str],
insecure: bool = False,
ca_data: Optional[str | bytes] = None,
):
super().__init__(url, "Posit Connect (SPCS)")
self.snowflake_connection_name = snowflake_connection_name
self.insecure = insecure
self.ca_data = ca_data
# for compatibility with RSConnectClient
self.cookie_jar = CookieJar()
self.api_key = api_key
self.bootstrap_jwt = None
def token_endpoint(self) -> str:
params = get_parameters(self.snowflake_connection_name)
if params is None:
raise RSConnectException("No Snowflake connection found.")
return "https://{}.snowflakecomputing.com/".format(params["account"])
def fmt_payload(self):
params = get_parameters(self.snowflake_connection_name)
if params is None:
raise RSConnectException("No Snowflake connection found.")
authenticator = params.get("authenticator")
if authenticator == "SNOWFLAKE_JWT":
spcs_url = urlparse(self.url)
scope = (
"session:role:{} {}".format(params["role"], spcs_url.netloc) if params.get("role") else spcs_url.netloc
)
jwt = generate_jwt(self.snowflake_connection_name)
grant_type = "urn:ietf:params:oauth:grant-type:jwt-bearer"
payload = {"scope": scope, "assertion": jwt, "grant_type": grant_type}
payload = urlencode(payload)
return {
"body": payload,
"headers": {"Content-Type": "application/x-www-form-urlencoded"},
"path": "/oauth/token",
}
elif authenticator == "oauth":
payload = {
"data": {
"AUTHENTICATOR": "OAUTH",
"TOKEN": params["token"],
}
}
return {
"body": payload,
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer %s" % params["token"],
"X-Snowflake-Authorization-Token-Type": "OAUTH",
},
"path": "/session/v1/login-request",
}
else:
raise NotImplementedError("Unsupported authenticator for SPCS Connect: %s" % authenticator)
def exchange_token(self) -> str:
try:
server = HTTPServer(url=self.token_endpoint())
payload = self.fmt_payload()
response = server.request(
method="POST", **payload # type: ignore[arg-type] # fmt_payload returns a dict with body and headers
)
response = cast(HTTPResponse, response)
# borrowed from AbstractRemoteServer.handle_bad_response
# since we don't want to pick up its json decoding assumptions
if response.status < 200 or response.status > 299:
raise RSConnectException(
"Received an unexpected response from %s (calling %s): %s %s"
% (
self.url,
response.full_uri,
response.status,
response.reason,
)
)
# Validate response body exists
if not response.response_body:
raise RSConnectException("Token exchange returned empty response")
# Ensure response body is decoded to string on the object
if isinstance(response.response_body, bytes):
response.response_body = response.response_body.decode("utf-8")
# Try to parse as JSON first
try:
import json
json_data = json.loads(response.response_body)
# If it's JSON, extract the token from data.token
if isinstance(json_data, dict) and "data" in json_data and "token" in json_data["data"]:
return json_data["data"]["token"]
else:
# JSON format doesn't match expected structure, return raw response
return response.response_body
except (json.JSONDecodeError, ValueError):
# Not JSON, return the raw response body
return response.response_body
except RSConnectException as e:
raise RSConnectException(f"Failed to exchange Snowflake token: {str(e)}") from e
TargetableServer = typing.Union[ShinyappsServer, RSConnectServer, CloudServer, SPCSConnectServer]
class S3Server(AbstractRemoteServer):
def __init__(self, url: str):
super().__init__(url, "S3")
class RSConnectClientDeployResult(TypedDict):
task_id: str | None
app_id: str
app_guid: str | None
app_url: str
draft_url: str | None
title: str | None
class RSConnectClient(HTTPServer):
def __init__(self, server: Union[RSConnectServer, SPCSConnectServer], cookies: Optional[CookieJar] = None):
if cookies is None:
cookies = server.cookie_jar
super().__init__(
append_to_path(server.url, "__api__"),
server.insecure,
server.ca_data,
cookies,
)
self._server = server
if server.api_key:
self.key_authorization(server.api_key)
if server.bootstrap_jwt:
self.bootstrap_authorization(server.bootstrap_jwt)
if server.snowflake_connection_name and isinstance(server, SPCSConnectServer):
token = server.exchange_token()
self.snowflake_authorization(token)
if server.api_key:
self._headers["X-RSC-Authorization"] = server.api_key
def _tweak_response(self, response: HTTPResponse) -> JsonData | HTTPResponse:
return (
response.json_data
if response.status and response.status >= 200 and response.status <= 299 and response.json_data is not None
else response
)
def me(self) -> UserRecord:
response = cast(Union[UserRecord, HTTPResponse], self.get("me"))
response = self._server.handle_bad_response(response)
return response
def bootstrap(self) -> BootstrapOutputDTO | HTTPResponse:
response = cast(Union[BootstrapOutputDTO, HTTPResponse], self.post("v1/experimental/bootstrap"))
# TODO: The place where bootstrap() is called expects a JSON object if the response is successfule, and a
# HTTPResponse if it is not; then it handles the error. This is different from the other methods, and probably
# should be changed in the future. For this to work, we will _not_ call .handle_bad_response() here at present.
# response = self._server.handle_bad_response(response)
return response
def server_settings(self) -> ServerSettings:
response = cast(Union[ServerSettings, HTTPResponse], self.get("server_settings"))
response = self._server.handle_bad_response(response)
return response
def python_settings(self) -> PyInfo:
response = cast(Union[PyInfo, HTTPResponse], self.get("v1/server_settings/python"))
response = self._server.handle_bad_response(response)
return response
def app_search(self, filters: Optional[Mapping[str, JsonData]]) -> AppSearchResults:
response = cast(Union[AppSearchResults, HTTPResponse], self.get("applications", query_params=filters))
response = self._server.handle_bad_response(response)
return response
def app_create(self, name: str) -> ContentItemV0:
response = cast(Union[ContentItemV0, HTTPResponse], self.post("applications", body={"name": name}))
response = self._server.handle_bad_response(response)
return response
def app_get(self, app_id: str) -> ContentItemV0:
response = cast(Union[ContentItemV0, HTTPResponse], self.get("applications/%s" % app_id))
response = self._server.handle_bad_response(response)
return response
def app_upload(self, app_id: str, tarball: typing.IO[bytes]) -> ContentItemV0:
response = cast(Union[ContentItemV0, HTTPResponse], self.post("applications/%s/upload" % app_id, body=tarball))
response = self._server.handle_bad_response(response)
return response
def app_update(self, app_id: str, updates: Mapping[str, str | None]) -> ContentItemV0:
response = cast(Union[ContentItemV0, HTTPResponse], self.post("applications/%s" % app_id, body=updates))
response = self._server.handle_bad_response(response)
return response
def app_add_environment_vars(self, app_guid: str, env_vars: list[tuple[str, str]]):
env_body = [dict(name=kv[0], value=kv[1]) for kv in env_vars]
return self.patch("v1/content/%s/environment" % app_guid, body=env_body)
def app_deploy(self, app_id: str, bundle_id: Optional[int] = None) -> TaskStatusV0:
response = cast(
Union[TaskStatusV0, HTTPResponse],
self.post("applications/%s/deploy" % app_id, body={"bundle": bundle_id}),
)
response = self._server.handle_bad_response(response)
return response
def app_config(self, app_id: str) -> ConfigureResult:
response = cast(Union[ConfigureResult, HTTPResponse], self.get("applications/%s/config" % app_id))
response = self._server.handle_bad_response(response)
return response
def is_app_failed_response(self, response: HTTPResponse | JsonData) -> bool:
return isinstance(response, HTTPResponse) and response.status >= 500
def app_access(self, app_guid: str) -> None:
method = "GET"
base = dirname(self._url.path) # remove __api__
path = f"{base}/content/{app_guid}/"
response = self._do_request(method, path, None, None, 3, {}, False)
if self.is_app_failed_response(response):
raise RSConnectException(
"Could not access the deployed content. "
+ "The app might not have started successfully."
+ f"\n\t For more information: {self.app_config(app_guid).get('logs_url')}"
)
def bundle_download(self, content_guid: str, bundle_id: str) -> HTTPResponse:
response = cast(
HTTPResponse,
self.get("v1/content/%s/bundles/%s/download" % (content_guid, bundle_id), decode_response=False),
)
response = self._server.handle_bad_response(response, is_httpresponse=True)
return response
def content_search(self) -> list[ContentItemV1]:
response = cast(Union[List[ContentItemV1], HTTPResponse], self.get("v1/content"))
response = self._server.handle_bad_response(response)
return response
def content_get(self, content_guid: str) -> ContentItemV1:
response = cast(Union[ContentItemV1, HTTPResponse], self.get("v1/content/%s" % content_guid))
response = self._server.handle_bad_response(response)
return response
def content_build(
self, content_guid: str, bundle_id: Optional[str] = None, activate: bool = True
) -> BuildOutputDTO:
body = {"bundle_id": bundle_id}
if not activate:
# The default behavior is to activate the app after building.
# So we only pass the parameter if we want to deactivate it.
# That way we can keep the API backwards compatible.
body["activate"] = False
response = cast(
Union[BuildOutputDTO, HTTPResponse],
self.post("v1/content/%s/build" % content_guid, body=body),
)
response = self._server.handle_bad_response(response)
return response
def content_deploy(self, app_guid: str, bundle_id: Optional[int] = None, activate: bool = True) -> BuildOutputDTO:
body = {"bundle_id": str(bundle_id)}
if not activate:
# The default behavior is to activate the app after deploying.
# So we only pass the parameter if we want to deactivate it.
# That way we can keep the API backwards compatible.
body["activate"] = False
response = cast(
Union[BuildOutputDTO, HTTPResponse],
self.post("v1/content/%s/deploy" % app_guid, body=body),
)
response = self._server.handle_bad_response(response)
return response
def system_caches_runtime_list(self) -> list[ListEntryOutputDTO]:
response = cast(Union[List[ListEntryOutputDTO], HTTPResponse], self.get("v1/system/caches/runtime"))
response = self._server.handle_bad_response(response)
return response
def system_caches_runtime_delete(self, target: DeleteInputDTO) -> DeleteOutputDTO:
response = cast(Union[DeleteOutputDTO, HTTPResponse], self.delete("v1/system/caches/runtime", body=target))
response = self._server.handle_bad_response(response)
return response
def task_get(
self,
task_id: str,
first: Optional[int] = None,
wait: Optional[int] = None,
) -> TaskStatusV1:
params = None
if first is not None or wait is not None:
params = {}
if first is not None:
params["first"] = first
if wait is not None:
params["wait"] = wait
response = cast(Union[TaskStatusV1, HTTPResponse], self.get("v1/tasks/%s" % task_id, query_params=params))
response = self._server.handle_bad_response(response)
# compatibility with rsconnect-jupyter
response["status"] = response["output"]
response["last_status"] = response["last"]
return response
def deploy(
self,
app_id: Optional[str],
app_name: Optional[str],
app_title: Optional[str],
title_is_default: bool,
tarball: IO[bytes],
env_vars: Optional[dict[str, str]] = None,
activate: bool = True,
) -> RSConnectClientDeployResult:
if app_id is None:
if app_name is None:
raise RSConnectException("An app ID or name is required to deploy an app.")
# create an app if id is not provided
app = self.app_create(app_name)
app_id = str(app["id"])
# Force the title to update.
title_is_default = False
else:
# assume app exists. if it was deleted then Connect will
# raise an error
try:
app = self.app_get(app_id)
except RSConnectException as e:
raise RSConnectException(f"{e} Try setting the --new flag to overwrite the previous deployment.") from e
app_guid = app["guid"]
if env_vars:
result = self.app_add_environment_vars(app_guid, list(env_vars.items()))
result = self._server.handle_bad_response(result)
if app["title"] != app_title and not title_is_default:
result = self.app_update(app_id, {"title": app_title})
result = self._server.handle_bad_response(result)
app["title"] = app_title
app_bundle = self.app_upload(app_id, tarball)
task = self.content_deploy(app_guid, app_bundle["id"], activate=activate)
# http://ADDRESS/DASHBOARD-PATH/#/apps/GUID/draft/BUNDLE_ID_TO_PREVIEW
# Pulling v1 content to get the full dashboard URL
app_v1 = self.content_get(app["guid"])
draft_url = app_v1["dashboard_url"] + f"/draft/{app_bundle['id']}"
return {
"task_id": task["task_id"],
"app_id": app_id,
"app_guid": app["guid"],
"app_url": app["url"],
"draft_url": draft_url if not activate else None,
"title": app["title"],
}
def download_bundle(self, content_guid: str, bundle_id: str) -> HTTPResponse:
results = self.bundle_download(content_guid, bundle_id)
return results
def search_content(self) -> list[ContentItemV1]:
results = self.content_search()
return results
def get_content(self, content_guid: str) -> ContentItemV1:
results = self.content_get(content_guid)
return results
def wait_for_task(
self,
task_id: str,
log_callback: Optional[Callable[[str], None]],
abort_func: Callable[[], bool] = lambda: False,
timeout: int = get_task_timeout(),
poll_wait: int = 1,
raise_on_error: bool = True,
) -> tuple[list[str] | None, TaskStatusV1]:
if log_callback is None:
log_lines: list[str] | None = []
log_callback = log_lines.append
else:
log_lines = None
first: int | None = None
start_time = time.time()
while True:
if (time.time() - start_time) > timeout:
raise RSConnectException(get_task_timeout_help_message(timeout))
elif abort_func():
raise RSConnectException("Task aborted.")
task = self.task_get(task_id, first=first, wait=poll_wait)
self.output_task_log(task, log_callback)
first = task["last"]
if task["finished"]:
result = task.get("result")
if isinstance(result, dict):
data = result.get("data", "")
type = result.get("type", "")
if data or type:
log_callback("%s (%s)" % (data, type))
err = task.get("error")
if err:
log_callback("Error from Connect server: " + err)
exit_code = task["code"]
if exit_code != 0:
exit_status = "Task exited with status %d." % exit_code
if raise_on_error:
raise RSConnectException(exit_status)
else:
log_callback("Task failed. %s" % exit_status)
return log_lines, task
@staticmethod
def output_task_log(
task: TaskStatusV1,
log_callback: Callable[[str], None],
):
"""Pipe any new output through the log_callback."""
for line in task["output"]:
log_callback(line)
# for backwards compatibility with rsconnect-jupyter
RSConnect = RSConnectClient
class ServerDetailsPython(TypedDict):
api_enabled: bool
versions: list[str]
class ServerDetails(TypedDict):
connect: str
python: ServerDetailsPython
class RSConnectExecutor:
def __init__(
self,
ctx: Optional[click.Context] = None,
name: Optional[str] = None,
url: Optional[str] = None,
api_key: Optional[str] = None,
snowflake_connection_name: Optional[str] = None,
insecure: bool = False,
cacert: Optional[str] = None,
ca_data: Optional[str | bytes] = None,
cookies: Optional[CookieJar] = None,
account: Optional[str] = None,
token: Optional[str] = None,
secret: Optional[str] = None,
timeout: int = 30,
logger: Optional[logging.Logger] = console_logger,
*,
path: Optional[str] = None,
server: Optional[str] = None,
exclude: Optional[tuple[str, ...]] = None,
new: Optional[bool] = None,
app_id: Optional[str] = None,
title: Optional[str] = None,
visibility: Optional[str] = None,
disable_env_management: Optional[bool] = None,
env_vars: Optional[dict[str, str]] = None,
) -> None:
self.remote_server: TargetableServer
self.client: RSConnectClient | PositClient
self.path = path or os.getcwd()
self.server = server
self.exclude = exclude
self.new = new
self.app_id = app_id
self.title = title or _default_title(self.path)
self.visibility = visibility
self.disable_env_management = disable_env_management
self.env_vars = env_vars
self.app_mode: AppMode | None = None
self.app_store: AppStore = AppStore(fake_module_file_from_directory(self.path))
self.app_store_version: int | None = None
self.api_key_is_required: bool | None = None
self.title_is_default: bool = not title
self.deployment_name: str | None = None
self.bundle: IO[bytes] | None = None
self.deployed_info: RSConnectClientDeployResult | None = None
self.logger: logging.Logger | None = logger
self.ctx = ctx
self.setup_remote_server(
ctx=ctx,
name=name,
url=url or server,
api_key=api_key,
snowflake_connection_name=snowflake_connection_name,
insecure=insecure,
cacert=cacert,
ca_data=ca_data,
account_name=account,
token=token,
secret=secret,
)
self.setup_client(cookies)
@classmethod
def fromConnectServer(
cls,
connect_server: RSConnectServer,
ctx: Optional[click.Context] = None,
cookies: Optional[CookieJar] = None,
account: Optional[str] = None,
token: Optional[str] = None,
secret: Optional[str] = None,
timeout: int = 30,
logger: Optional[logging.Logger] = console_logger,
*,
path: Optional[str] = None,
server: Optional[str] = None,
exclude: Optional[tuple[str, ...]] = None,
new: Optional[bool] = None,
app_id: Optional[str] = None,
title: Optional[str] = None,
visibility: Optional[str] = None,
disable_env_management: Optional[bool] = None,
env_vars: Optional[dict[str, str]] = None,
):
return cls(
ctx=ctx,
url=connect_server.url,
api_key=connect_server.api_key,
insecure=connect_server.insecure,
ca_data=connect_server.ca_data,
cookies=cookies,
account=account,
token=token,
secret=secret,
timeout=timeout,
logger=logger,
path=path,
server=server,
exclude=exclude,
new=new,
app_id=app_id,
title=title,
visibility=visibility,
disable_env_management=disable_env_management,
env_vars=env_vars,
)
def output_overlap_header(self, previous: bool) -> bool:
if self.logger and not previous:
self.logger.warning(
"\nConnect detected CLI commands and/or environment variables that overlap with stored credential.\n"
)
self.logger.warning(
"Check your environment variables (e.g. CONNECT_API_KEY) to make sure you want them to be used.\n"
)
self.logger.warning(
"Credential parameters are taken with the following precedence: stored > CLI > environment.\n"
)
self.logger.warning(
"To ignore an environment variable, override it in the CLI with an empty string (e.g. -k '').\n\n"
)
return True
else:
return False
def output_overlap_details(self, cli_param: str, previous: bool):
new_previous = self.output_overlap_header(previous)
sourceName = validation.get_parameter_source_name_from_ctx(cli_param, self.ctx)
if self.logger is not None:
self.logger.warning(f">> stored {cli_param} value overrides the {cli_param} value from {sourceName}\n")
return new_previous
def setup_remote_server(
self,
ctx: Optional[click.Context],
name: Optional[str] = None,
url: Optional[str] = None,
api_key: Optional[str] = None,
snowflake_connection_name: Optional[str] = None,
insecure: bool = False,
cacert: Optional[str] = None,
ca_data: Optional[str | bytes] = None,
account_name: Optional[str] = None,
token: Optional[str] = None,
secret: Optional[str] = None,
):
validation.validate_connection_options(
ctx=ctx,
url=url,
api_key=api_key,
snowflake_connection_name=snowflake_connection_name,
insecure=insecure,
cacert=cacert,
account_name=account_name,
token=token,
secret=secret,
name=name,
)
# The validation.validate_connection_options() function ensures that certain
# combinations of arguments are present; the cast() calls inside of the
# if-statements below merely reflect these validations.
header_output = False
if cacert and not ca_data:
ca_data = read_certificate_file(cacert)
server_data = ServerStore().resolve(name, url)
if server_data.from_store:
url = server_data.url
if self.logger:
if server_data.api_key and api_key:
header_output = self.output_overlap_details("api-key", header_output)
if server_data.snowflake_connection_name and snowflake_connection_name:
header_output = self.output_overlap_details("snowflake_connection_name", header_output)
if server_data.insecure and insecure:
header_output = self.output_overlap_details("insecure", header_output)
if server_data.ca_data and ca_data:
header_output = self.output_overlap_details("cacert", header_output)
if server_data.account_name and account_name:
header_output = self.output_overlap_details("account", header_output)
if server_data.token and token:
header_output = self.output_overlap_details("token", header_output)
if server_data.secret and secret:
header_output = self.output_overlap_details("secret", header_output)
if header_output:
self.logger.warning("\n")
api_key = api_key or server_data.api_key
snowflake_connection_name = snowflake_connection_name or server_data.snowflake_connection_name
insecure = insecure or server_data.insecure
ca_data = ca_data or server_data.ca_data
account_name = account_name or server_data.account_name
token = token or server_data.token
secret = secret or server_data.secret
self.is_server_from_store = server_data.from_store
if snowflake_connection_name:
url = cast(str, url)
self.remote_server = SPCSConnectServer(url, api_key, snowflake_connection_name, insecure, ca_data)
elif api_key:
url = cast(str, url)
self.remote_server = RSConnectServer(url, api_key, insecure, ca_data)
elif token and secret:
if url and ("rstudio.cloud" in url or "posit.cloud" in url):
account_name = cast(str, account_name)
self.remote_server = CloudServer(url, account_name, token, secret)
else:
url = cast(str, url)
account_name = cast(str, account_name)
self.remote_server = ShinyappsServer(url, account_name, token, secret)
else:
raise RSConnectException("Unable to infer Connect server type and setup server.")
def setup_client(self, cookies: Optional[CookieJar] = None):
if isinstance(self.remote_server, RSConnectServer):
self.client = RSConnectClient(self.remote_server, cookies)
elif isinstance(self.remote_server, SPCSConnectServer):
self.client = RSConnectClient(self.remote_server)
elif isinstance(self.remote_server, PositServer):
self.client = PositClient(self.remote_server)
else:
raise RSConnectException("Unable to infer Connect client.")
def pipe(self, func: Callable[P, T], *args: P.args, **kwargs: P.kwargs):
return func(*args, **kwargs)
@cls_logged("Validating server...")
def validate_server(self):
"""
Validate that there is enough information to talk to shinyapps.io or a Connect server.
"""
if isinstance(self.remote_server, SPCSConnectServer):
self.validate_spcs_server()
elif isinstance(self.remote_server, RSConnectServer):
self.validate_connect_server()
elif isinstance(self.remote_server, PositServer):
self.validate_posit_server()
else:
raise RSConnectException("Unable to validate server from information provided.")
return self
def validate_connect_server(self):
if not isinstance(self.remote_server, RSConnectServer):
raise RSConnectException("remote_server must be a Connect server.")
url = self.remote_server.url
api_key = self.remote_server.api_key
insecure = self.remote_server.insecure
api_key_is_required = self.api_key_is_required
ca_data = self.remote_server.ca_data
server_data = ServerStore().resolve(None, url)
connect_server = RSConnectServer(url, None, insecure, ca_data)
# If our info came from the command line, make sure the URL really works.
if not server_data.from_store:
self.server_settings()
connect_server.api_key = api_key
if not connect_server.api_key:
if api_key_is_required:
raise RSConnectException('An API key must be specified for "%s".' % connect_server.url)
return self
# If our info came from the command line, make sure the key really works.
if not server_data.from_store:
self.verify_api_key(connect_server)
self.remote_server = connect_server
self.client = RSConnectClient(self.remote_server)
return self
def validate_spcs_server(self):
if not isinstance(self.remote_server, SPCSConnectServer):
raise RSConnectException("remote_server must be a Connect server in SPCS")
url = self.remote_server.url
api_key = self.remote_server.api_key