hucl 0.0.1__py3-none-any.whl

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.
hucl/__about__.py ADDED
@@ -0,0 +1,4 @@
1
+ # SPDX-FileCopyrightText: 2026-present Angus Hollands <goosey15@gmail.com>
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ __version__ = "0.0.1"
hucl/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ # SPDX-FileCopyrightText: 2026-present Angus Hollands <goosey15@gmail.com>
2
+ #
3
+ # SPDX-License-Identifier: MIT
hucl/__main__.py ADDED
@@ -0,0 +1,9 @@
1
+ # SPDX-FileCopyrightText: 2026-present Angus Hollands <goosey15@gmail.com>
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ import sys
5
+
6
+ if __name__ == "__main__":
7
+ from hucl.cli import hucl
8
+
9
+ sys.exit(hucl())
hucl/cli/__init__.py ADDED
@@ -0,0 +1,27 @@
1
+ # SPDX-FileCopyrightText: 2026-present Angus Hollands <goosey15@gmail.com>
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ import argparse
5
+ import logging
6
+ import os
7
+
8
+ from .start import setup_cli as add_start
9
+ from .stop import setup_cli as add_stop
10
+
11
+
12
+ def main(argv: list[str] = None):
13
+ logging.basicConfig(
14
+ filename="hucl.log",
15
+ level=os.environ.get("JUPYTERHUB_CLIENT_LOGLEVEL", "INFO"),
16
+ )
17
+
18
+ parser = argparse.ArgumentParser()
19
+ subparsers = parser.add_subparsers(required=True)
20
+ add_start(subparsers.add_parser("start"))
21
+ add_stop(subparsers.add_parser("stop"))
22
+ args = parser.parse_args()
23
+ args.impl(args)
24
+
25
+
26
+ if __name__ == "__main__":
27
+ main()
hucl/cli/start.py ADDED
@@ -0,0 +1,38 @@
1
+ import argparse
2
+ import logging
3
+
4
+ from ..flows.start import ensure_api_url, start_server_sansio
5
+ from ..drivers.sync import sync_driver
6
+
7
+
8
+ def setup_cli(parser: argparse.ArgumentParser):
9
+ parser.add_argument("url", help="JupyterHub API URL")
10
+ parser.add_argument("token", help="JupyterHub API Token")
11
+ parser.add_argument("--server", help="Server name")
12
+ parser.add_argument(
13
+ "-v", "--verbose", help="Turn on verbose debugging", action="store_true"
14
+ )
15
+ parser.add_argument(
16
+ "--profile-option",
17
+ help="Profile option key-value pair of the form key=value",
18
+ nargs="*",
19
+ action="extend",
20
+ default=[],
21
+ )
22
+ parser.set_defaults(impl=handle_args)
23
+ return parser
24
+
25
+
26
+ def handle_args(args: argparse.Namespace):
27
+ logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO)
28
+
29
+ # Arg processing
30
+ api_url = ensure_api_url(args.url)
31
+ server_name = args.server
32
+ api_token = args.token
33
+ profile_options = {k: v for k, v in (p.split("=") for p in args.profile_option)}
34
+
35
+ server_url = sync_driver(
36
+ start_server_sansio(api_url, api_token, server_name, profile_options)
37
+ )
38
+ print(repr(server_url))
hucl/cli/stop.py ADDED
@@ -0,0 +1,32 @@
1
+ import argparse
2
+ import logging
3
+
4
+ from ..flows.stop import ensure_api_url, stop_server_sansio
5
+ from ..drivers.sync import sync_driver
6
+
7
+
8
+ def setup_cli(parser: argparse.ArgumentParser):
9
+ parser.add_argument("url", help="JupyterHub API URL")
10
+ parser.add_argument("token", help="JupyterHub API Token")
11
+ parser.add_argument("--server", help="Server name")
12
+ parser.add_argument(
13
+ "-v", "--verbose", help="Turn on verbose debugging", action="store_true"
14
+ )
15
+ parser.add_argument(
16
+ "--remove",
17
+ help="Delete the server once it has stopped",
18
+ action="store_true",
19
+ )
20
+ parser.set_defaults(impl=handle_args)
21
+ return parser
22
+
23
+
24
+ def handle_args(args: argparse.Namespace):
25
+ logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO)
26
+
27
+ # Arg processing
28
+ api_url = ensure_api_url(args.url)
29
+ server_name = args.server
30
+ api_token = args.token
31
+
32
+ sync_driver(stop_server_sansio(api_url, api_token, server_name, args.remove))
hucl/drivers/async.py ADDED
@@ -0,0 +1,47 @@
1
+ import asyncio
2
+ import contextlib
3
+ import urllib.request
4
+ import urllib.parse
5
+ import logging
6
+
7
+ from .sansio import SansioImpl, Sleep, Read, ReadLine, Close, NetworkResponse
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ async def async_driver(loop: SansioImpl):
13
+ import aiohttp.client
14
+
15
+ async with aiohttp.ClientSession() as session, contextlib.AsyncExitStack() as stack:
16
+ response = None
17
+ while True:
18
+ logger.debug("Send event response", response)
19
+ try:
20
+ request = loop.send(response)
21
+ except StopIteration as err:
22
+ return err.value
23
+ logger.debug("Receive event", request)
24
+
25
+ response = None
26
+ match request:
27
+ case Sleep(duration_s):
28
+ await asyncio.sleep(duration_s)
29
+ case Read(readable):
30
+ assert isinstance(readable, NetworkResponse)
31
+ response = await readable._impl.content.read()
32
+ case ReadLine(readable):
33
+ assert isinstance(readable, NetworkResponse)
34
+ response = await readable._impl.content.readline()
35
+ case Close(closable):
36
+ assert isinstance(readable._impl, NetworkResponse)
37
+ closable.close()
38
+ case urllib.request.Request():
39
+ resp = await stack.enter_async_context(
40
+ session.request(
41
+ request.get_method(),
42
+ request.get_full_url(),
43
+ headers=dict(request.header_items()),
44
+ data=request.data,
45
+ )
46
+ )
47
+ response = NetworkResponse(resp.status, resp.headers, resp)
hucl/drivers/sansio.py ADDED
@@ -0,0 +1,36 @@
1
+ import dataclasses
2
+ import urllib.request
3
+
4
+ from typing import Any, Generator
5
+
6
+
7
+ @dataclasses.dataclass
8
+ class Read:
9
+ readable: Any
10
+
11
+
12
+ @dataclasses.dataclass
13
+ class ReadLine:
14
+ readable: Any
15
+
16
+
17
+ @dataclasses.dataclass
18
+ class Close:
19
+ closable: Any
20
+
21
+
22
+ @dataclasses.dataclass
23
+ class Sleep:
24
+ duration_s: Any
25
+
26
+
27
+ @dataclasses.dataclass
28
+ class NetworkResponse:
29
+ status: int
30
+ headers: dict
31
+ _impl: Any
32
+
33
+
34
+ type Request = Sleep | Read | ReadLine | Close | urllib.request.Request
35
+ type Response = bytes | bytearray | NetworkResponse | None
36
+ type SansioImpl = Generator[Request, Response, str]
hucl/drivers/sync.py ADDED
@@ -0,0 +1,38 @@
1
+ import urllib.request
2
+ import urllib.parse
3
+ import contextlib
4
+ import logging
5
+ import time
6
+
7
+ from .sansio import SansioImpl, Sleep, Read, ReadLine, Close, NetworkResponse
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ def sync_driver(loop: SansioImpl):
13
+ response = None
14
+ with contextlib.ExitStack() as stack:
15
+ while True:
16
+ logger.debug(f"Send event response: {response!r}")
17
+ try:
18
+ request = loop.send(response)
19
+ except StopIteration as err:
20
+ return err.value
21
+ logger.debug(f"Receive event: {request!r}")
22
+
23
+ response = None
24
+ match request:
25
+ case Sleep(duration_s):
26
+ time.sleep(duration_s)
27
+ case Read(readable):
28
+ assert isinstance(readable, NetworkResponse)
29
+ response = readable._impl.read()
30
+ case ReadLine(readable):
31
+ assert isinstance(readable, NetworkResponse)
32
+ response = readable._impl.readline()
33
+ case Close(closable):
34
+ assert isinstance(closable, NetworkResponse)
35
+ closable._impl.close()
36
+ case urllib.request.Request():
37
+ f = stack.enter_context(urllib.request.urlopen(request))
38
+ response = NetworkResponse(f.status, f.headers, f)
hucl/flows/start.py ADDED
@@ -0,0 +1,139 @@
1
+ import urllib.request
2
+ import urllib.parse
3
+ import json
4
+ import random
5
+ import enum
6
+ import logging
7
+ from typing import cast, NewType
8
+
9
+ from ..drivers.sansio import SansioImpl, Read, ReadLine, Sleep
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ DATA_PREFIX = b"data: "
14
+ RANDOM_REQUESTS_PER_MIN = 10
15
+
16
+
17
+ type APIUrl = NewType("APIUrl", str)
18
+
19
+
20
+ class State(enum.StrEnum):
21
+ check_status = enum.auto()
22
+ start_server = enum.auto()
23
+ wait_for_start = enum.auto()
24
+ wait_for_stop = enum.auto()
25
+
26
+
27
+ def ensure_api_url(maybe_url: str) -> APIUrl:
28
+ return cast(APIUrl, maybe_url.rstrip("/"))
29
+
30
+
31
+ def get_server_api_url(api_url: APIUrl, user_name: str, server_name: str | None) -> str:
32
+ server_path = "/server" if server_name is None else f"/servers/{server_name}"
33
+ return f"{api_url}/users/{user_name}{server_path}"
34
+
35
+
36
+ def start_server_sansio(
37
+ api_url: APIUrl,
38
+ api_token: str,
39
+ server_name: str | None,
40
+ profile_options: dict[str, str],
41
+ ) -> SansioImpl:
42
+ """
43
+ Basic reconciliation loop for starting a (named) server on a JupyterHub.
44
+ Existing servers with the same name (or default, not given) will be re-used.
45
+
46
+ :param api_url: URL for JupyterHub API endpoint
47
+ """
48
+ auth_headers = {"Authorization": f"token {api_token}"}
49
+
50
+ # Initial state
51
+ state = State.check_status
52
+
53
+ # State data (side effects)
54
+ user_name: str
55
+
56
+ while True:
57
+ logger.debug(state)
58
+ match state:
59
+ case State.check_status:
60
+ # Get current user
61
+ resp = yield urllib.request.Request(
62
+ f"{api_url}/user", headers=auth_headers
63
+ )
64
+ content = yield Read(resp)
65
+
66
+ user_model = json.loads(content)
67
+
68
+ # Is the server known of?
69
+ existing_server = user_model["servers"].get(server_name or "")
70
+ user_name = user_model["name"]
71
+
72
+ # Transition
73
+ match existing_server:
74
+ case None:
75
+ state = State.start_server
76
+ case {"pending": "start", **rest}:
77
+ state = State.wait_for_start
78
+ case {"pending": "stop", **rest}:
79
+ state = State.wait_for_stop
80
+ case _:
81
+ assert existing_server["ready"]
82
+ return existing_server["url"]
83
+
84
+ case State.start_server:
85
+ # Try to start server
86
+ resp = yield urllib.request.Request(
87
+ get_server_api_url(api_url, user_name, server_name),
88
+ method="POST",
89
+ data=json.dumps(profile_options).encode("utf-8"),
90
+ headers={**auth_headers, "Content-Type": "application/json"},
91
+ )
92
+
93
+ # Handle response
94
+ match resp.status:
95
+ # Server already running
96
+ case 201:
97
+ state = State.check_status
98
+ case 202:
99
+ state = State.wait_for_start
100
+ case 429:
101
+ retry_after = resp.headers.get("Retry-After")
102
+ delay = (
103
+ random.expovariate(RANDOM_REQUESTS_PER_MIN / 60)
104
+ if retry_after is None
105
+ else float(retry_after)
106
+ )
107
+ logger.info(
108
+ f"Server asked us to back off, waiting for {delay:.1f} seconds"
109
+ )
110
+ yield Sleep(delay)
111
+ case _:
112
+ raise RuntimeError(resp.status)
113
+
114
+ case State.wait_for_start:
115
+ # Get URL
116
+ resp = yield (
117
+ urllib.request.Request(
118
+ f"{get_server_api_url(api_url, user_name, server_name)}/progress",
119
+ method="GET",
120
+ headers=auth_headers,
121
+ )
122
+ )
123
+ while True:
124
+ line = yield ReadLine(resp)
125
+ if not line.startswith(DATA_PREFIX):
126
+ continue
127
+
128
+ logger.debug(line.decode())
129
+
130
+ # Load JSON response line
131
+ line_data = json.loads(line[len(DATA_PREFIX) :].decode())
132
+ if line_data.get("ready"):
133
+ return line_data["url"]
134
+
135
+ case State.wait_for_stop:
136
+ delay = random.expovariate(RANDOM_REQUESTS_PER_MIN / 60)
137
+ logger.info(f"Waiting for server to stop for {delay:.1f} seconds")
138
+ yield Sleep(delay)
139
+ state = State.check_status
hucl/flows/stop.py ADDED
@@ -0,0 +1,106 @@
1
+ import urllib.request
2
+ import urllib.parse
3
+ import json
4
+ import random
5
+ import enum
6
+ import logging
7
+ from typing import cast, NewType
8
+
9
+ from ..drivers.sansio import SansioImpl, Read, ReadLine, Sleep
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ RANDOM_REQUESTS_PER_MIN = 10
14
+
15
+
16
+ type APIUrl = NewType("APIUrl", str)
17
+
18
+
19
+ class State(enum.StrEnum):
20
+ check_status = enum.auto()
21
+ stop_server = enum.auto()
22
+ wait_for_stop = enum.auto()
23
+
24
+
25
+ def ensure_api_url(maybe_url: str) -> APIUrl:
26
+ return cast(APIUrl, maybe_url.rstrip("/"))
27
+
28
+
29
+ def get_server_api_url(api_url: APIUrl, user_name: str, server_name: str | None) -> str:
30
+ server_path = "/server" if server_name is None else f"/servers/{server_name}"
31
+ return f"{api_url}/users/{user_name}{server_path}"
32
+
33
+
34
+ def stop_server_sansio(
35
+ api_url: APIUrl,
36
+ api_token: str,
37
+ server_name: str | None,
38
+ remove: bool,
39
+ ) -> SansioImpl:
40
+ """
41
+ Basic reconciliation loop for stopping a (named) server on a JupyterHub.
42
+
43
+ :param api_url: URL for JupyterHub API endpoint
44
+ """
45
+ auth_headers = {"Authorization": f"token {api_token}"}
46
+
47
+ # Initial state
48
+ state = State.check_status
49
+
50
+ # State data (side effects)
51
+ user_name: str
52
+
53
+ while True:
54
+ logger.debug(state)
55
+ match state:
56
+ case State.check_status:
57
+ # Get current user
58
+ resp = yield urllib.request.Request(
59
+ f"{api_url}/user", headers=auth_headers
60
+ )
61
+ content = yield Read(resp)
62
+
63
+ user_model = json.loads(content)
64
+
65
+ # Is the server known of?
66
+ existing_server = user_model["servers"].get(server_name or "")
67
+ user_name = user_model["name"]
68
+
69
+ # Transition
70
+ match existing_server:
71
+ # Doesn't exist
72
+ case None:
73
+ # Done
74
+ return
75
+ case {"pending": "stop", **rest}:
76
+ state = State.wait_for_stop
77
+ case _:
78
+ # Running
79
+ state = State.stop_server
80
+
81
+ case State.stop_server:
82
+ # Try to start server
83
+ resp = yield urllib.request.Request(
84
+ get_server_api_url(api_url, user_name, server_name),
85
+ method="DELETE",
86
+ data=json.dumps({"remove": remove}).encode("utf-8"),
87
+ headers={**auth_headers, "Content-Type": "application/json"},
88
+ )
89
+
90
+ # Handle response
91
+ match resp.status:
92
+ # Server already running
93
+ case 202:
94
+ # Server stopping
95
+ state = State.wait_for_stop
96
+ case 204:
97
+ # Server already stopped (but not removed)
98
+ return
99
+ case _:
100
+ raise RuntimeError(resp.status)
101
+
102
+ case State.wait_for_stop:
103
+ delay = random.expovariate(RANDOM_REQUESTS_PER_MIN / 60)
104
+ logger.info(f"Waiting for server to stop for {delay:.1f} seconds")
105
+ yield Sleep(delay)
106
+ state = State.check_status
@@ -0,0 +1,51 @@
1
+ Metadata-Version: 2.4
2
+ Name: hucl
3
+ Version: 0.0.1
4
+ Summary: A simple client to initialise a JupyterHub server
5
+ Project-URL: Documentation, https://github.com/Angus Hollands/hucl#readme
6
+ Project-URL: Issues, https://github.com/Angus Hollands/hucl/issues
7
+ Project-URL: Source, https://github.com/Angus Hollands/hucl
8
+ Author-email: Angus Hollands <goosey15@gmail.com>
9
+ License-Expression: MIT
10
+ License-File: LICENSE.txt
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Programming Language :: Python
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Classifier: Programming Language :: Python :: Implementation :: CPython
16
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
17
+ Requires-Python: >=3.13
18
+ Description-Content-Type: text/markdown
19
+
20
+ # hucl
21
+
22
+ [![PyPI - Version](https://img.shields.io/pypi/v/hucl.svg)](https://pypi.org/project/hucl)
23
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/hucl.svg)](https://pypi.org/project/hucl)
24
+
25
+ -----
26
+
27
+ ## Table of Contents
28
+
29
+ - [Installation](#installation)
30
+ - [License](#license)
31
+
32
+ ## Installation
33
+
34
+ ```console
35
+ pip install hucl
36
+ ```
37
+
38
+ ## Usage
39
+ ```bash
40
+ hucl start https://my-hub.com/hub/api <TOKEN>
41
+ ```
42
+
43
+ ## License
44
+
45
+ `hucl` is distributed under the terms of the [MIT](https://spdx.org/licenses/MIT.html) license.
46
+
47
+ ## Design
48
+
49
+ This CLI and library uses a [sansio](https://sans-io.readthedocs.io/) approach for splitting IO from logic. This makes it very easy to test and abstract out event-loop implementations (by implementing a smaller event loop!).
50
+
51
+ I did this for fun — I've been telling people to do this for years without ever actually implementing such an approach in my own libraries.
@@ -0,0 +1,16 @@
1
+ hucl/__about__.py,sha256=jqjwwKOE5Otqb5FXXv7dPHd27pBNy71xCiapy-CX10M,130
2
+ hucl/__init__.py,sha256=17qsWd55KjqhePO7F7uHiHL-qpjf4H3h0ZbcgnnC2uM,108
3
+ hucl/__main__.py,sha256=E0BTl5_lMADtDxX2v3k9DseKK9PQ4Dpl6e3Aj5QcL_M,199
4
+ hucl/cli/__init__.py,sha256=Ba2Vx1NJjho_JwQV1lZfb2akQueMyEWuit0siaCxeXE,671
5
+ hucl/cli/start.py,sha256=pTz6Z4v_uica0YZa3Rv1w_RM2shuyDoGvIsYviR0YNk,1192
6
+ hucl/cli/stop.py,sha256=62TpC8D6km08VSpeScwSs3C48ZPH-n9el8Dbh2MiKeA,988
7
+ hucl/drivers/async.py,sha256=WTiLyXgYe_CZ9161rcrYYHaqIghyid8mBW0uDntkTZo,1788
8
+ hucl/drivers/sansio.py,sha256=uAI-hif2aPEl-FqyKhVXlRKI3C118OFzeEAeNFlNEuw,586
9
+ hucl/drivers/sync.py,sha256=UICCmXzpfqxZvYgl0ATIsJjPkxijSwRPgoHPL_PTXJw,1377
10
+ hucl/flows/start.py,sha256=d8R-qLBjb4vszGjbtPitLWa3ak-cQ51n70u46WPSo9k,4749
11
+ hucl/flows/stop.py,sha256=R3mo7cuNcOxbObPKlowUp2-7LkXAfB_Vew1osKCypQE,3266
12
+ hucl-0.0.1.dist-info/METADATA,sha256=6aOR6EYxcVo4V1HP772vKpV0UmQFdWeT1jkgHF8ZMvI,1700
13
+ hucl-0.0.1.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
14
+ hucl-0.0.1.dist-info/entry_points.txt,sha256=VqC2eqIXa7bd4TLC5ttsxd4ncZmDjlUKhLRZBM7J8u0,39
15
+ hucl-0.0.1.dist-info/licenses/LICENSE.txt,sha256=s6mCZNgsnQoFGM6yIDIS3soC8rzIjfH6gcsCChmh46c,1100
16
+ hucl-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ hucl = hucl.cli:main
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026-present Angus Hollands <goosey15@gmail.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.