psytricks 2.2.0a22__tar.gz → 2.4.0a0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (19) hide show
  1. {psytricks-2.2.0a22 → psytricks-2.4.0a0}/PKG-INFO +2 -1
  2. {psytricks-2.2.0a22 → psytricks-2.4.0a0}/pyproject.toml +1 -1
  3. {psytricks-2.2.0a22 → psytricks-2.4.0a0}/src/psytricks/__init__.py +1 -1
  4. {psytricks-2.2.0a22 → psytricks-2.4.0a0}/src/psytricks/__ps1__/psytricks-lib.ps1 +1 -1
  5. psytricks-2.4.0a0/src/psytricks/exceptions.py +84 -0
  6. {psytricks-2.2.0a22 → psytricks-2.4.0a0}/src/psytricks/wrapper.py +126 -19
  7. {psytricks-2.2.0a22 → psytricks-2.4.0a0}/INSTALLATION.md +0 -0
  8. {psytricks-2.2.0a22 → psytricks-2.4.0a0}/LICENSE +0 -0
  9. {psytricks-2.2.0a22 → psytricks-2.4.0a0}/README.md +0 -0
  10. {psytricks-2.2.0a22 → psytricks-2.4.0a0}/src/psytricks/__ps1__/psytricks-wrapper.ps1 +0 -0
  11. {psytricks-2.2.0a22 → psytricks-2.4.0a0}/src/psytricks/__ps1__/restricks-server.example.xml +0 -0
  12. {psytricks-2.2.0a22 → psytricks-2.4.0a0}/src/psytricks/__ps1__/restricks-server.ps1 +0 -0
  13. {psytricks-2.2.0a22 → psytricks-2.4.0a0}/src/psytricks/__ps1__/sampledata/GetAccessUsers.json +0 -0
  14. {psytricks-2.2.0a22 → psytricks-2.4.0a0}/src/psytricks/__ps1__/sampledata/GetMachineStatus.json +0 -0
  15. {psytricks-2.2.0a22 → psytricks-2.4.0a0}/src/psytricks/__ps1__/sampledata/GetSessions.json +0 -0
  16. {psytricks-2.2.0a22 → psytricks-2.4.0a0}/src/psytricks/cli.py +0 -0
  17. {psytricks-2.2.0a22 → psytricks-2.4.0a0}/src/psytricks/decoder.py +0 -0
  18. {psytricks-2.2.0a22 → psytricks-2.4.0a0}/src/psytricks/literals.py +0 -0
  19. {psytricks-2.2.0a22 → psytricks-2.4.0a0}/src/psytricks/mappings.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: psytricks
3
- Version: 2.2.0a22
3
+ Version: 2.4.0a0
4
4
  Summary: PowerShell Python Citrix Tricks.
5
5
  License-Expression: GPL-3.0-or-later
6
6
  License-File: LICENSE
@@ -14,6 +14,7 @@ Classifier: Programming Language :: Python :: 3.11
14
14
  Classifier: Programming Language :: Python :: 3.12
15
15
  Classifier: Programming Language :: Python :: 3.13
16
16
  Classifier: Programming Language :: Python :: 3.14
17
+ Classifier: Programming Language :: Python :: 3.15
17
18
  Requires-Dist: click (>=8.1.3,<9.0.0)
18
19
  Requires-Dist: loguru (>=0.7.0,<0.8.0)
19
20
  Requires-Dist: requests (>=2.30.0,<3.0.0)
@@ -6,7 +6,7 @@ authors = [
6
6
  ]
7
7
  license = "GPL-3.0-or-later"
8
8
  dynamic = ["readme"]
9
- version = "2.2.0-a.22"
9
+ version = "2.4.0-a.0"
10
10
 
11
11
  [tool.poetry]
12
12
  documentation = "https://imcf.one/apidocs/psytricks/psytricks.html"
@@ -3,7 +3,7 @@
3
3
  .. include:: ../../CHANGELOG.md
4
4
  """
5
5
 
6
- __version__ = "2.2.0-a.22"
6
+ __version__ = "2.4.0-a.0"
7
7
 
8
8
  # style exceptions for pdoc-include-only docstrings:
9
9
  # ruff: noqa: D400 (missing-trailing-period)
@@ -5,7 +5,7 @@ Collection of functions and other definitions to be sourced by other scripts.
5
5
  #>
6
6
 
7
7
  # the version variable will be filled by poetry at build time:
8
- $Version = "2.2.0-a.22"
8
+ $Version = "2.4.0-a.0"
9
9
 
10
10
 
11
11
  #region properties-selectors
@@ -0,0 +1,84 @@
1
+ """PSyTricks exception classes."""
2
+
3
+ import requests
4
+
5
+
6
+ class ResTricksConnectionError(requests.exceptions.ConnectionError, ConnectionError):
7
+ """Communicating with the ResTricks server failed.
8
+
9
+ Raised by `psytricks.wrapper.ResTricksWrapper` instead of the low-level
10
+ exceptions of `requests` / `urllib3` in case the server couldn't be reached
11
+ or didn't answer in time, using a concise message that states
12
+ the request method, the URL and the root cause of the failure (e.g.
13
+ `ConnectionRefusedError: [Errno 111] Connection refused`).
14
+
15
+ The class derives from both, `requests.exceptions.ConnectionError` and the
16
+ built-in `ConnectionError`, so existing code catching either of them will
17
+ continue to work.
18
+
19
+ The (potentially long) chain of underlying exceptions is suppressed when
20
+ raising this exception to keep tracebacks short, but the original exception
21
+ is still accessible through the `original` attribute (and `__context__`).
22
+
23
+ Parameters
24
+ ----------
25
+ message : str
26
+ The exception message.
27
+ method : str, optional
28
+ The HTTP method of the failed request (e.g. `GET`).
29
+ url : str, optional
30
+ The URL of the failed request.
31
+ original : Exception, optional
32
+ The exception that triggered this one.
33
+
34
+ Attributes
35
+ ----------
36
+ method : str or None
37
+ See the constructor for details.
38
+ url : str or None
39
+ See the constructor for details.
40
+ original : Exception or None
41
+ See the constructor for details.
42
+ reason : Exception or None
43
+ The innermost exception in the chain of `original`, i.e. the actual
44
+ root cause (e.g. a `ConnectionRefusedError` or `TimeoutError`).
45
+ """
46
+
47
+ def __init__(
48
+ self,
49
+ message: str,
50
+ method: str | None = None,
51
+ url: str | None = None,
52
+ original: Exception | None = None,
53
+ ):
54
+ super().__init__(message)
55
+ self.method = method
56
+ self.url = url
57
+ self.original = original
58
+ self.reason = root_cause(original) if original is not None else None
59
+
60
+
61
+ def root_cause(ex: BaseException) -> BaseException:
62
+ """Find the innermost exception in the chain of the given one.
63
+
64
+ Follows `__cause__` (explicit chaining via `raise ... from ...`) and falls
65
+ back to `__context__` (implicit chaining, "during handling of the above
66
+ exception...") until the end of the chain is reached.
67
+
68
+ Parameters
69
+ ----------
70
+ ex : BaseException
71
+ The exception to start from.
72
+
73
+ Returns
74
+ -------
75
+ BaseException
76
+ The innermost exception of the chain (`ex` itself if it isn't chained).
77
+ """
78
+ seen = {id(ex)} # guard against (theoretically possible) cycles
79
+ while True:
80
+ nxt = ex.__cause__ or ex.__context__
81
+ if nxt is None or id(nxt) in seen:
82
+ return ex
83
+ seen.add(id(nxt))
84
+ ex = nxt
@@ -1,10 +1,9 @@
1
1
  """PowerShell Python Citrix Tricks."""
2
2
 
3
- import subprocess
4
3
  import json
5
4
  import os
5
+ import subprocess
6
6
  import time
7
-
8
7
  from os.path import dirname
9
8
  from pathlib import Path
10
9
  from sys import platform
@@ -14,7 +13,17 @@ from loguru import logger as log
14
13
 
15
14
  from . import __version__
16
15
  from .decoder import parse_powershell_json
17
- from .literals import Action, RequestName, MsgStyle
16
+ from .literals import Action, MsgStyle, RequestName
17
+ from .exceptions import ResTricksConnectionError, root_cause
18
+
19
+ # `requests` exceptions to be converted into a `ResTricksConnectionError`, i.e.
20
+ # the server couldn't be reached or didn't answer in time - other exceptions
21
+ # (e.g. `MissingSchema`, `InvalidHeader`) indicate a misconfiguration or a bug
22
+ # and are re-raised unchanged instead:
23
+ _CONNECTION_ERRORS = (
24
+ requests.exceptions.ConnectionError,
25
+ requests.exceptions.Timeout,
26
+ )
18
27
 
19
28
 
20
29
  class ResTricksWrapper:
@@ -63,6 +72,7 @@ class ResTricksWrapper:
63
72
  self._connected = False
64
73
  self._verify = verify
65
74
  self._read_only = False
75
+ self._dump_responses_to = None
66
76
 
67
77
  if not lazy:
68
78
  self.connect()
@@ -91,15 +101,52 @@ class ResTricksWrapper:
91
101
  log.debug(f"{verb} 'read-only' mode.")
92
102
  self._read_only = value
93
103
 
104
+ @property
105
+ def dump_responses_to(self) -> Path | None:
106
+ """Path to dump responses to - **DO NOT USE IN PRODUCTION**.
107
+
108
+ Default: `None`, meaning responses will **not** be written to disk.
109
+
110
+ If `dump_responses_to` is set to a valid path, any response returned
111
+ from a request will be dumped to a file in that path. Each dump is
112
+ placed in a single file with the following naming pattern with the
113
+ components described below:
114
+
115
+ `<command>-<method>-<status>-<timestamp>.txt`
116
+
117
+ * `<command>`: e.g. `GetSessions`, `SetMaintenanceMode`
118
+ * `<method>`: one of [`GET`, `POST`]
119
+ * `<status>`: the HTTP status of the response
120
+ * `<timestamp>`: milliseconds since the epoch
121
+
122
+ This is intended for debugging and may also be used to craft data mocks
123
+ based on real data that can be used for testing.
124
+
125
+ Notes
126
+ -----
127
+ Existing files will **NOT** be overwritten, no matter how unlikely this
128
+ is given the above naming scheme.
129
+ """
130
+ return self._dump_responses_to
131
+
132
+ @dump_responses_to.setter
133
+ def dump_responses_to(self, value: Path | None) -> None:
134
+ if value and not (value.is_dir() and value.exists()):
135
+ log.error(f"Path needs to be an existing directory: {value}")
136
+ return
137
+
138
+ target = str(value) if value else "<INACTIVE>"
139
+ log.debug(f"Setting 'dump-responses' path: {target}")
140
+ self._dump_responses_to = value
141
+
94
142
  def connect(self) -> None:
95
143
  """Connect to the ResTricks service unless already connected.
96
144
 
97
145
  Raises
98
146
  ------
99
- ValueError
100
- Raised in case the server version doesn't match the local version.
101
- ConnectionError
102
- Raised in case the initial connection check failed.
147
+ ResTricksConnectionError
148
+ Raised in case the initial connection check failed (including a
149
+ mismatching server version), unless `verify` was set to `False`.
103
150
  """
104
151
  if self._connected:
105
152
  log.trace("Connection 🔌 established previously, not reconnecting.")
@@ -122,10 +169,16 @@ class ResTricksWrapper:
122
169
  self._connected = True
123
170
 
124
171
  except Exception as ex: # pylint: disable-msg=broad-except
125
- if self._verify:
126
- raise ConnectionError(
127
- f"Connecting to {self.base_url} failed: {ex}"
128
- ) from ex
172
+ if not self._verify:
173
+ return
174
+ # already a concise exception from send_get_request(), don't wrap it:
175
+ if isinstance(ex, ResTricksConnectionError):
176
+ raise
177
+ raise ResTricksConnectionError(
178
+ f"Connecting to {self.base_url} failed: {ex}",
179
+ url=self.base_url,
180
+ original=ex,
181
+ ) from ex
129
182
 
130
183
  def validate_version(self, server_ver) -> bool:
131
184
  """Validate the server version against the local module.
@@ -186,9 +239,36 @@ class ResTricksWrapper:
186
239
  log.error("Version mismatch! 🧨")
187
240
  return False
188
241
 
189
- @staticmethod
190
- def _check_response(response) -> None:
242
+ def _request_failed(
243
+ self, method: str, raw_url: str, ex: Exception
244
+ ) -> ResTricksConnectionError:
245
+ """Log a failed request and create a concise exception for it.
246
+
247
+ Parameters
248
+ ----------
249
+ method : str
250
+ The HTTP method of the failed request (e.g. `GET`).
251
+ raw_url : str
252
+ The part of the URL that was appended to `self.base_url`.
253
+ ex : Exception
254
+ The exception raised by `requests`, one of `_CONNECTION_ERRORS`.
255
+
256
+ Returns
257
+ -------
258
+ ResTricksConnectionError
259
+ The exception to be raised by the caller (using `from None` to
260
+ suppress the chain of low-level exceptions).
261
+ """
262
+ url = self.base_url + raw_url
263
+ reason = root_cause(ex)
264
+ msg = f"{method} request [{url}] failed: {type(reason).__name__}: {reason}"
265
+ log.error(msg)
266
+ return ResTricksConnectionError(msg, method=method, url=url, original=ex)
267
+
268
+ def _check_response(self, response: requests.Response) -> None:
191
269
  """Check the HTTP response code and JSON status attributes."""
270
+ self._write_response_dump(response)
271
+
192
272
  if response.status_code == 200:
193
273
  return
194
274
 
@@ -209,6 +289,29 @@ class ResTricksWrapper:
209
289
  log.warning(response.text)
210
290
  raise ValueError(f"Malformed response: {response.text}") from ex
211
291
 
292
+ def _write_response_dump(self, response: requests.Response) -> Path | None:
293
+ """Dump the response to disk if `dump_responses_to` is set."""
294
+ if not self.dump_responses_to:
295
+ return
296
+
297
+ try:
298
+ timestamp = int(time.time_ns() / 1000000)
299
+ method = response.request.method
300
+ url = str(response.request.url)
301
+ log.trace(f"🌐 Request URL: {url}")
302
+ command = url.removeprefix(self.base_url).replace("/", "-")
303
+ status = str(response.status_code)
304
+ filename = f"{command}-{method}-{status}-{timestamp}.txt"
305
+ full_path = self.dump_responses_to / filename
306
+ log.warning(f"🚚 Dumping response to 🗃️: {full_path}")
307
+ if full_path.exists():
308
+ raise FileExistsError(f"File already exists: {full_path}")
309
+
310
+ with open(full_path, "w", encoding="utf8") as outfile:
311
+ outfile.write(response.text)
312
+ except Exception as ex:
313
+ log.error(f"🔥 Error dumping response: {ex}")
314
+
212
315
  def send_get_request(
213
316
  self, raw_url: str, auto_conn: bool = True
214
317
  ) -> list[dict] | dict | None:
@@ -237,9 +340,11 @@ class ResTricksWrapper:
237
340
  response = requests.get(
238
341
  self.base_url + raw_url, timeout=self.timeout, headers=self.headers
239
342
  )
343
+ except _CONNECTION_ERRORS as ex:
344
+ raise self._request_failed("GET", raw_url, ex) from None
240
345
  except Exception as ex: # pylint: disable-msg=broad-except
241
- log.error(f"GET request [{raw_url}] failed: {ex}")
242
- raise ex
346
+ log.error(f"GET request [{raw_url}] failed unexpectedly: {ex}")
347
+ raise
243
348
 
244
349
  try:
245
350
  data = response.json(object_hook=parse_powershell_json)
@@ -258,7 +363,7 @@ class ResTricksWrapper:
258
363
  log.error(f"{msg}\n== STATUS CODE:{response.status_code}")
259
364
  raise json.JSONDecodeError(msg, doc=response.text, pos=0)
260
365
 
261
- ResTricksWrapper._check_response(response)
366
+ self._check_response(response)
262
367
 
263
368
  return data
264
369
 
@@ -315,11 +420,13 @@ class ResTricksWrapper:
315
420
  timeout=self.timeout,
316
421
  headers=self.headers,
317
422
  )
423
+ except _CONNECTION_ERRORS as ex:
424
+ raise self._request_failed("POST", raw_url, ex) from None
318
425
  except Exception as ex: # pylint: disable-msg=broad-except
319
- log.error(f"POST request [{raw_url}] failed: {ex}")
320
- raise ex
426
+ log.error(f"POST request [{raw_url}] failed unexpectedly: {ex}")
427
+ raise
321
428
 
322
- ResTricksWrapper._check_response(response)
429
+ self._check_response(response)
323
430
 
324
431
  if no_json:
325
432
  log.debug(f"No-payload response status code: {response.status_code}")
File without changes
File without changes