hucl 0.0.1__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.
@@ -0,0 +1,58 @@
1
+ # .github/workflows/ci-cd.yml
2
+ on:
3
+ release:
4
+ types:
5
+ - published
6
+
7
+ name: Release
8
+
9
+ jobs:
10
+ release-build:
11
+ name: Build package
12
+ runs-on: ubuntu-latest
13
+ steps:
14
+ # retrieve your distributions here
15
+ - name: Checkout
16
+ uses: actions/checkout@v6
17
+
18
+ - uses: actions/setup-python@v6
19
+ with:
20
+ python-version: "3.x"
21
+
22
+ - name: Build release distributions
23
+ run: |
24
+ # NOTE: put your own distribution build steps here.
25
+ python -m pip install build
26
+ python -m build
27
+
28
+ - name: Upload distributions
29
+ uses: actions/upload-artifact@v6
30
+ with:
31
+ name: release-dists
32
+ path: dist/
33
+
34
+ pypi-publish:
35
+ runs-on: ubuntu-latest
36
+ name: Upload to PyPI
37
+
38
+ needs:
39
+ - release-build
40
+
41
+ permissions:
42
+ # IMPORTANT: this permission is mandatory for trusted publishing
43
+ id-token: write
44
+
45
+ environment:
46
+ name: pypi
47
+ url: https://pypi.org/p/hucl
48
+
49
+ steps:
50
+ - name: Retrieve release distributions
51
+ uses: actions/download-artifact@v7
52
+ with:
53
+ name: release-dists
54
+ path: dist/
55
+
56
+ - name: Publish release distributions to PyPI
57
+ uses: pypa/gh-action-pypi-publish@release/v1
58
+
hucl-0.0.1/.gitignore ADDED
@@ -0,0 +1,218 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ # Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ # poetry.lock
109
+ # poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ # pdm.lock
116
+ # pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ # pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # Redis
135
+ *.rdb
136
+ *.aof
137
+ *.pid
138
+
139
+ # RabbitMQ
140
+ mnesia/
141
+ rabbitmq/
142
+ rabbitmq-data/
143
+
144
+ # ActiveMQ
145
+ activemq-data/
146
+
147
+ # SageMath parsed files
148
+ *.sage.py
149
+
150
+ # Environments
151
+ .env
152
+ .envrc
153
+ .venv
154
+ env/
155
+ venv/
156
+ ENV/
157
+ env.bak/
158
+ venv.bak/
159
+
160
+ # Spyder project settings
161
+ .spyderproject
162
+ .spyproject
163
+
164
+ # Rope project settings
165
+ .ropeproject
166
+
167
+ # mkdocs documentation
168
+ /site
169
+
170
+ # mypy
171
+ .mypy_cache/
172
+ .dmypy.json
173
+ dmypy.json
174
+
175
+ # Pyre type checker
176
+ .pyre/
177
+
178
+ # pytype static type analyzer
179
+ .pytype/
180
+
181
+ # Cython debug symbols
182
+ cython_debug/
183
+
184
+ # PyCharm
185
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
186
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
187
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
188
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
189
+ # .idea/
190
+
191
+ # Abstra
192
+ # Abstra is an AI-powered process automation framework.
193
+ # Ignore directories containing user credentials, local state, and settings.
194
+ # Learn more at https://abstra.io/docs
195
+ .abstra/
196
+
197
+ # Visual Studio Code
198
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
199
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
200
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
201
+ # you could uncomment the following to ignore the entire vscode folder
202
+ # .vscode/
203
+ # Temporary file for partial code execution
204
+ tempCodeRunnerFile.py
205
+
206
+ # Ruff stuff:
207
+ .ruff_cache/
208
+
209
+ # PyPI configuration file
210
+ .pypirc
211
+
212
+ # Marimo
213
+ marimo/_static/
214
+ marimo/_lsp/
215
+ __marimo__/
216
+
217
+ # Streamlit
218
+ .streamlit/secrets.toml
hucl-0.0.1/LICENSE.txt ADDED
@@ -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.
hucl-0.0.1/PKG-INFO ADDED
@@ -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.
hucl-0.0.1/README.md ADDED
@@ -0,0 +1,32 @@
1
+ # hucl
2
+
3
+ [![PyPI - Version](https://img.shields.io/pypi/v/hucl.svg)](https://pypi.org/project/hucl)
4
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/hucl.svg)](https://pypi.org/project/hucl)
5
+
6
+ -----
7
+
8
+ ## Table of Contents
9
+
10
+ - [Installation](#installation)
11
+ - [License](#license)
12
+
13
+ ## Installation
14
+
15
+ ```console
16
+ pip install hucl
17
+ ```
18
+
19
+ ## Usage
20
+ ```bash
21
+ hucl start https://my-hub.com/hub/api <TOKEN>
22
+ ```
23
+
24
+ ## License
25
+
26
+ `hucl` is distributed under the terms of the [MIT](https://spdx.org/licenses/MIT.html) license.
27
+
28
+ ## Design
29
+
30
+ 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!).
31
+
32
+ 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,65 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "hucl"
7
+ dynamic = ["version"]
8
+ description = 'A simple client to initialise a JupyterHub server'
9
+ readme = "README.md"
10
+ requires-python = ">=3.13"
11
+ license = "MIT"
12
+ keywords = []
13
+ authors = [
14
+ { name = "Angus Hollands", email = "goosey15@gmail.com" },
15
+ ]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Programming Language :: Python",
19
+ "Programming Language :: Python :: 3.13",
20
+ "Programming Language :: Python :: 3.14",
21
+ "Programming Language :: Python :: Implementation :: CPython",
22
+ "Programming Language :: Python :: Implementation :: PyPy",
23
+ ]
24
+ dependencies = [
25
+ ]
26
+
27
+ [dependency-groups]
28
+ test = ["pytest>7", "coverage"]
29
+
30
+ [project.urls]
31
+ Documentation = "https://github.com/Angus Hollands/hucl#readme"
32
+ Issues = "https://github.com/Angus Hollands/hucl/issues"
33
+ Source = "https://github.com/Angus Hollands/hucl"
34
+
35
+ [project.scripts]
36
+ hucl = "hucl.cli:main"
37
+
38
+ [tool.hatch.version]
39
+ path = "src/hucl/__about__.py"
40
+
41
+ [tool.hatch.envs.types]
42
+ extra-dependencies = [
43
+ "mypy>=1.0.0",
44
+ ]
45
+ [tool.hatch.envs.types.scripts]
46
+ check = "mypy --install-types --non-interactive {args:src/hucl tests}"
47
+
48
+ [tool.coverage.run]
49
+ source_pkgs = ["hucl", "tests"]
50
+ branch = true
51
+ parallel = true
52
+ omit = [
53
+ "src/hucl/__about__.py",
54
+ ]
55
+
56
+ [tool.coverage.paths]
57
+ hucl = ["src/hucl", "*/hucl/src/hucl"]
58
+ tests = ["tests", "*/hucl/tests"]
59
+
60
+ [tool.coverage.report]
61
+ exclude_lines = [
62
+ "no cov",
63
+ "if __name__ == .__main__.:",
64
+ "if TYPE_CHECKING:",
65
+ ]
@@ -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"
@@ -0,0 +1,3 @@
1
+ # SPDX-FileCopyrightText: 2026-present Angus Hollands <goosey15@gmail.com>
2
+ #
3
+ # SPDX-License-Identifier: MIT
@@ -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())
@@ -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()
@@ -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))
@@ -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))
@@ -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)
@@ -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]
@@ -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)
@@ -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
@@ -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,3 @@
1
+ # SPDX-FileCopyrightText: 2026-present Angus Hollands <goosey15@gmail.com>
2
+ #
3
+ # SPDX-License-Identifier: MIT
@@ -0,0 +1,245 @@
1
+ from hucl.flows.start import start_server_sansio
2
+ from hucl.drivers.sansio import Read, ReadLine, NetworkResponse, Sleep
3
+ import urllib.request
4
+ import json
5
+ import pytest
6
+
7
+
8
+ def test_unnamed_already_exists():
9
+ flow = start_server_sansio("http://my-hub.com/hub/api", "123456-a-token", None, {})
10
+
11
+ # First, it should request the user model
12
+ request = flow.send(None)
13
+ assert isinstance(request, urllib.request.Request)
14
+ assert request.get_full_url() == "http://my-hub.com/hub/api/user"
15
+ assert request.get_method() == "GET"
16
+
17
+ # We send our 200 response and then a token
18
+ response = NetworkResponse(200, {}, object())
19
+ request = flow.send(response)
20
+
21
+ # Ensure it's reading this obj
22
+ assert isinstance(request, Read)
23
+ assert request.readable is response
24
+
25
+ # Ensure that we get the proper result!
26
+ with pytest.raises(StopIteration, match=r"/user/bob"):
27
+ request = flow.send(
28
+ json.dumps(
29
+ {"name": "bob", "servers": {"": {"ready": True, "url": "/user/bob"}}}
30
+ ).encode("utf-8")
31
+ )
32
+
33
+
34
+ def test_unnamed_doesnt_exist_is_created():
35
+ flow = start_server_sansio("http://my-hub.com/hub/api", "123456-a-token", None, {})
36
+
37
+ # First, Flow should request the user model
38
+ request = flow.send(None)
39
+ assert isinstance(request, urllib.request.Request)
40
+ assert request.get_method() == "GET"
41
+ assert request.get_full_url() == "http://my-hub.com/hub/api/user"
42
+
43
+ # We send our 200 response and then a token
44
+ response = NetworkResponse(200, {}, object())
45
+ request = flow.send(response)
46
+
47
+ # Ensure Flow's reading this obj
48
+ assert isinstance(request, Read)
49
+ assert request.readable is response
50
+
51
+ # Ensure that we get the proper result!
52
+ request = flow.send(json.dumps({"name": "bob", "servers": {}}).encode("utf-8"))
53
+ assert isinstance(request, urllib.request.Request)
54
+ assert request.get_method() == "POST"
55
+ assert request.get_full_url() == "http://my-hub.com/hub/api/users/bob/server"
56
+
57
+ ######### Option 1: HTTP 201 #############
58
+ # Send HTTP 201 Created response
59
+ request = flow.send(NetworkResponse(201, {}, object()))
60
+
61
+ # Flow again should check the status
62
+ assert isinstance(request, urllib.request.Request)
63
+ assert request.get_method() == "GET"
64
+ assert request.get_full_url() == "http://my-hub.com/hub/api/user"
65
+
66
+ # We send our 200 response and then a token
67
+ response = NetworkResponse(200, {}, response)
68
+ request = flow.send(response)
69
+
70
+ # Ensure Flow's reading this obj
71
+ assert isinstance(request, Read)
72
+ assert request.readable is response
73
+
74
+ # Ensure that we get the proper result!
75
+ with pytest.raises(StopIteration, match=r"/user/bob/"):
76
+ request = flow.send(
77
+ json.dumps(
78
+ {"name": "bob", "servers": {"": {"ready": True, "url": "/user/bob/"}}}
79
+ ).encode("utf-8")
80
+ )
81
+
82
+
83
+ def test_unnamed_doesnt_exist_is_accepted():
84
+ flow = start_server_sansio("http://my-hub.com/hub/api", "123456-a-token", None, {})
85
+
86
+ # First, Flow should request the user model
87
+ request = flow.send(None)
88
+ assert isinstance(request, urllib.request.Request)
89
+ assert request.get_method() == "GET"
90
+ assert request.get_full_url() == "http://my-hub.com/hub/api/user"
91
+
92
+ # We send our 200 response and then a token
93
+ response = NetworkResponse(200, {}, object())
94
+ request = flow.send(response)
95
+
96
+ # Ensure Flow's reading this obj
97
+ assert isinstance(request, Read)
98
+ assert request.readable is response
99
+
100
+ # Ensure that we get the proper result!
101
+ request = flow.send(json.dumps({"name": "bob", "servers": {}}).encode("utf-8"))
102
+ assert isinstance(request, urllib.request.Request)
103
+ assert request.get_method() == "POST"
104
+ assert request.get_full_url() == "http://my-hub.com/hub/api/users/bob/server"
105
+
106
+ ######### Option 2: HTTP 202 #############
107
+ # Send HTTP 202 Accepted response
108
+ request = flow.send(NetworkResponse(202, {}, object()))
109
+
110
+ # Flow again should check the status
111
+ assert isinstance(request, urllib.request.Request)
112
+ assert request.get_method() == "GET"
113
+ assert (
114
+ request.get_full_url() == "http://my-hub.com/hub/api/users/bob/server/progress"
115
+ )
116
+
117
+ # We send our 200 response and then a token
118
+ response = NetworkResponse(200, {}, response)
119
+ request = flow.send(response)
120
+
121
+ # Ensure Flow's reading this progress
122
+ assert isinstance(request, ReadLine)
123
+ assert request.readable is response
124
+
125
+ request = flow.send(b"some random data")
126
+ assert isinstance(request, ReadLine)
127
+ assert request.readable is response
128
+
129
+ request = flow.send(b"some other data")
130
+ assert isinstance(request, ReadLine)
131
+ assert request.readable is response
132
+
133
+ request = flow.send(b'data: {"url": "http://some-url"}')
134
+ assert isinstance(request, ReadLine)
135
+ assert request.readable is response
136
+
137
+ request = flow.send(b'data: {"ready": false, "url": "/user/bob/"}')
138
+ assert isinstance(request, ReadLine)
139
+ assert request.readable is response
140
+
141
+ # Ensure that we get the proper result!
142
+ with pytest.raises(StopIteration, match=r"/user/bob/"):
143
+ flow.send(b'data: {"ready": true, "url": "/user/bob/"}')
144
+
145
+
146
+ def test_unnamed_doesnt_exist_needs_retry():
147
+ flow = start_server_sansio("http://my-hub.com/hub/api", "123456-a-token", None, {})
148
+
149
+ # First, Flow should request the user model
150
+ request = flow.send(None)
151
+ assert isinstance(request, urllib.request.Request)
152
+ assert request.get_method() == "GET"
153
+ assert request.get_full_url() == "http://my-hub.com/hub/api/user"
154
+
155
+ # We send our 200 response and then a token
156
+ response = NetworkResponse(200, {}, object())
157
+ request = flow.send(response)
158
+
159
+ # Ensure Flow's reading this obj
160
+ assert isinstance(request, Read)
161
+ assert request.readable is response
162
+
163
+ # Ensure that we get the proper result!
164
+ request = flow.send(json.dumps({"name": "bob", "servers": {}}).encode("utf-8"))
165
+ assert isinstance(request, urllib.request.Request)
166
+ assert request.get_method() == "POST"
167
+ assert request.get_full_url() == "http://my-hub.com/hub/api/users/bob/server"
168
+
169
+ ######### Option 3: HTTP 429 #############
170
+ # Send 429 Too Many Requests response
171
+ request = flow.send(NetworkResponse(429, {"Retry-After": "5"}, object()))
172
+
173
+ # Flow again should check the status
174
+ assert isinstance(request, Sleep)
175
+ assert request.duration_s == 5
176
+
177
+ # We continue
178
+ request = flow.send(None)
179
+
180
+ # Flow asks us to create again
181
+ assert isinstance(request, urllib.request.Request)
182
+ assert request.get_method() == "POST"
183
+ assert request.get_full_url() == "http://my-hub.com/hub/api/users/bob/server"
184
+
185
+
186
+ def test_unnamed_exists_stopping():
187
+ flow = start_server_sansio("http://my-hub.com/hub/api", "123456-a-token", None, {})
188
+
189
+ # First, Flow should request the user model
190
+ request = flow.send(None)
191
+ assert isinstance(request, urllib.request.Request)
192
+ assert request.get_method() == "GET"
193
+ assert request.get_full_url() == "http://my-hub.com/hub/api/user"
194
+
195
+ # We send our 200 response and then a token
196
+ response = NetworkResponse(200, {}, object())
197
+ request = flow.send(response)
198
+
199
+ # Ensure Flow's reading this obj
200
+ assert isinstance(request, Read)
201
+ assert request.readable is response
202
+
203
+ # Ensure that we get the proper result!
204
+ request = flow.send(
205
+ json.dumps(
206
+ {
207
+ "name": "bob",
208
+ "servers": {
209
+ "": {
210
+ "ready": False,
211
+ "stopped": False,
212
+ "pending": "stop",
213
+ "url": "/user/bob/",
214
+ }
215
+ },
216
+ }
217
+ ).encode("utf-8")
218
+ )
219
+
220
+ # Flow will wait and check status
221
+ assert isinstance(request, Sleep)
222
+
223
+ # We continue
224
+ request = flow.send(None)
225
+
226
+ # Flow will check the status again
227
+ assert isinstance(request, urllib.request.Request)
228
+ assert request.get_full_url() == "http://my-hub.com/hub/api/user"
229
+ assert request.get_method() == "GET"
230
+
231
+ # We send our 200 response and then a token
232
+ response = NetworkResponse(200, {}, object())
233
+ request = flow.send(response)
234
+
235
+ # Ensure it's reading this obj
236
+ assert isinstance(request, Read)
237
+ assert request.readable is response
238
+
239
+ # Ensure that we get the proper result!
240
+ with pytest.raises(StopIteration, match=r"/user/bob"):
241
+ request = flow.send(
242
+ json.dumps(
243
+ {"name": "bob", "servers": {"": {"ready": True, "url": "/user/bob"}}}
244
+ ).encode("utf-8")
245
+ )