trailhead-edu 0.2.0__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.
trailhead/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Trailhead's Python teaching server."""
2
+
3
+ __version__ = "0.2.0"
trailhead/__main__.py ADDED
@@ -0,0 +1,117 @@
1
+ """Command-line entry point for the Trailhead server."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from pathlib import Path
7
+ import sys
8
+ from typing import Sequence
9
+
10
+ import uvicorn
11
+
12
+ from . import __version__
13
+ from .project import set_project_root
14
+ from .websocket_origin import (
15
+ ALLOWED_ORIGINS_ENV,
16
+ add_allowed_websocket_origins,
17
+ )
18
+
19
+ PACKAGE_DIR = Path(__file__).resolve().parent
20
+
21
+
22
+ def _port(value: str) -> int:
23
+ port = int(value)
24
+ if not 1 <= port <= 65535:
25
+ raise argparse.ArgumentTypeError("port must be between 1 and 65535")
26
+ return port
27
+
28
+
29
+ def _url_host(host: str) -> str:
30
+ """Format a bind host for display in an HTTP URL."""
31
+
32
+ if ":" in host and not host.startswith("["):
33
+ return f"[{host}]"
34
+ return host
35
+
36
+
37
+ def build_parser() -> argparse.ArgumentParser:
38
+ """Build Trailhead's command-line argument parser."""
39
+
40
+ parser = argparse.ArgumentParser(description="Run the Trailhead server")
41
+ parser.add_argument(
42
+ "--host",
43
+ default="127.0.0.1",
44
+ help="interface to bind (default: 127.0.0.1)",
45
+ )
46
+ parser.add_argument(
47
+ "--port",
48
+ "-p",
49
+ type=_port,
50
+ default=1110,
51
+ help="TCP port to bind (default: 1110)",
52
+ )
53
+ parser.add_argument(
54
+ "--root",
55
+ type=Path,
56
+ default=Path.cwd(),
57
+ help="project containing the Python modules to serve (default: current directory)",
58
+ )
59
+ parser.add_argument(
60
+ "--reload",
61
+ action="store_true",
62
+ help="restart when Trailhead server source files change",
63
+ )
64
+ parser.add_argument(
65
+ "--log-level",
66
+ choices=("critical", "error", "warning", "info", "debug", "trace"),
67
+ default="info",
68
+ help="Uvicorn log level (default: info)",
69
+ )
70
+ parser.add_argument(
71
+ "--allow-origin",
72
+ action="append",
73
+ default=[],
74
+ metavar="ORIGIN",
75
+ help=(
76
+ "allow an exact browser WebSocket origin (repeatable; additional "
77
+ f"origins may be set with {ALLOWED_ORIGINS_ENV})"
78
+ ),
79
+ )
80
+ parser.add_argument("--version", action="version", version=__version__)
81
+ return parser
82
+
83
+
84
+ def main(argv: Sequence[str] | None = None) -> int:
85
+ """Run Trailhead using an installable, host-independent configuration."""
86
+
87
+ args = build_parser().parse_args(argv)
88
+ try:
89
+ project_root = set_project_root(args.root)
90
+ add_allowed_websocket_origins(args.allow_origin)
91
+ except (OSError, ValueError) as error:
92
+ print(f"trailhead: {error}", file=sys.stderr)
93
+ return 2
94
+
95
+ print(f"Serving project {project_root}")
96
+ print(f"Starting Trailhead server at http://{_url_host(args.host)}:{args.port}")
97
+ print("Press Ctrl+C to stop the Trailhead server")
98
+
99
+ options: dict[str, object] = {
100
+ "host": args.host,
101
+ "port": args.port,
102
+ "log_level": args.log_level,
103
+ }
104
+ if args.reload:
105
+ options.update(
106
+ reload=True,
107
+ reload_dirs=[str(PACKAGE_DIR)],
108
+ )
109
+
110
+ # An import string works both normally and in Uvicorn's spawned reload
111
+ # worker. Any startup/import failure remains visible to the caller.
112
+ uvicorn.run("trailhead.app:app", **options) # type: ignore[arg-type]
113
+ return 0
114
+
115
+
116
+ if __name__ == "__main__":
117
+ raise SystemExit(main())
@@ -0,0 +1 @@
1
+ """Static analysis helpers for Python source modules."""
@@ -0,0 +1,206 @@
1
+ """Tools for analyzing Python code."""
2
+
3
+ from _ast import AsyncFor
4
+ import argparse
5
+ import ast
6
+ import tokenize
7
+ from typing import Any, Dict
8
+ from pydantic import BaseModel
9
+
10
+
11
+ class Parameter(BaseModel):
12
+ name: str
13
+ type: str
14
+
15
+
16
+ class Function(BaseModel):
17
+ name: str
18
+ doc: str
19
+ parameters: list[Parameter]
20
+ return_type: str
21
+ source: str
22
+
23
+
24
+ class Module(BaseModel):
25
+ name: str
26
+ doc: str
27
+ top_level_functions: list[Function]
28
+ top_level_calls: list[str]
29
+ global_vars: Dict[str, Any]
30
+
31
+
32
+ def main() -> None:
33
+ parser = argparse.ArgumentParser(description="Analyze Python Code")
34
+ parser.add_argument("filepath", help="The Python file to analyze")
35
+ args = parser.parse_args()
36
+ file = args.filepath
37
+ with tokenize.open(file) as source:
38
+ tree = ast.parse(source.read())
39
+ module = get_module(file, tree)
40
+ print(module)
41
+
42
+
43
+ def analyze_module(file: str) -> Module:
44
+ with tokenize.open(file) as source:
45
+ try:
46
+ tree = ast.parse(source.read())
47
+ return get_module(file, tree)
48
+ except Exception as e:
49
+ return Module(
50
+ name=file,
51
+ doc=f"{type(e).__name__} encountered when parsing",
52
+ top_level_functions=[],
53
+ top_level_calls=[],
54
+ global_vars={},
55
+ )
56
+
57
+
58
+ def get_module(path: str, tree: ast.Module) -> Module:
59
+ return Module(
60
+ name=path,
61
+ doc=ast.get_docstring(tree) or "",
62
+ top_level_functions=get_module_function_definitions(tree),
63
+ top_level_calls=get_top_level_function_calls(tree),
64
+ global_vars=extract_global_vars(tree),
65
+ )
66
+
67
+
68
+ def extract_global_vars(tree: ast.Module) -> Dict[str, Any]:
69
+ assignment_nodes: list[ast.Assign | ast.AnnAssign] = []
70
+ for n in tree.body:
71
+ if isinstance(n, ast.Assign) and isinstance(n.targets[0], ast.Name):
72
+ assignment_nodes.append(n)
73
+ elif isinstance(n, ast.AnnAssign) and isinstance(n.target, ast.Name):
74
+ assignment_nodes.append(n)
75
+
76
+ variable_dict = {}
77
+ for node in assignment_nodes:
78
+ if isinstance(node, ast.AnnAssign):
79
+ if not isinstance(node.target, ast.Name):
80
+ continue
81
+ ref = node.target.id
82
+ value = node.value
83
+ else:
84
+ target = node.targets[0]
85
+ if not isinstance(target, ast.Name):
86
+ continue
87
+ ref = target.id
88
+ value = node.value
89
+
90
+ if isinstance(value, (ast.Constant, ast.List, ast.Tuple)):
91
+ assignment_value = ast.literal_eval(value)
92
+ elif isinstance(value, ast.Dict):
93
+ assignment_value = {}
94
+ for key, val in zip(value.keys, value.values):
95
+ if key is None:
96
+ continue
97
+ if isinstance(val, (ast.Constant, ast.List, ast.Tuple, ast.Dict)):
98
+ assignment_value[ast.literal_eval(key)] = ast.literal_eval(val)
99
+ else:
100
+ assignment_value[ast.literal_eval(key)] = str(val)
101
+ else:
102
+ assignment_value = None
103
+
104
+ variable_dict[ref] = assignment_value
105
+
106
+ return variable_dict
107
+
108
+
109
+ def get_module_function_definitions(tree: ast.AST) -> list[Function]:
110
+ class FunctionCollector(ast.NodeVisitor):
111
+ def __init__(self):
112
+ self.functions: list[Function] = []
113
+
114
+ def visit_ClassDef(self, node: ast.ClassDef):
115
+ # Not looking for method definitions
116
+ ...
117
+
118
+ def visit_FunctionDef(self, node: ast.FunctionDef):
119
+ ast_params = node.args.args
120
+ parameters = [
121
+ Parameter(name=param.arg, type=self._get_param_type(param.annotation))
122
+ for param in ast_params
123
+ ]
124
+ self.functions.append(
125
+ Function(
126
+ name=node.name,
127
+ doc=ast.get_docstring(node) or "",
128
+ parameters=parameters,
129
+ return_type=self._get_return_type(node.returns),
130
+ source=ast.unparse(node),
131
+ )
132
+ )
133
+
134
+ def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef):
135
+ return self.visit_FunctionDef(node) # type: ignore
136
+
137
+ def _get_param_type(self, node: ast.expr | None) -> str:
138
+ if node is None:
139
+ return "Any"
140
+ elif isinstance(node, ast.Name):
141
+ return node.id
142
+ elif isinstance(node, ast.Constant):
143
+ return str(node.value)
144
+ else:
145
+ return "UnsupportedParamType"
146
+
147
+ def _get_return_type(self, node: ast.expr | None) -> str:
148
+ if isinstance(node, ast.Name):
149
+ return node.id
150
+ elif isinstance(node, ast.Constant):
151
+ return str(node.value)
152
+ else:
153
+ return "UnsupportedReturnType"
154
+
155
+ function_collector = FunctionCollector()
156
+ function_collector.visit(tree)
157
+ return function_collector.functions
158
+
159
+
160
+ def get_top_level_function_calls(tree: ast.AST) -> list[str]:
161
+ class FunctionCallCollector(ast.NodeVisitor):
162
+ def __init__(self):
163
+ self.function_calls: list[str] = []
164
+
165
+ def visit_Call(self, node: ast.Call):
166
+ self.function_calls.append(ast.unparse(node.func))
167
+
168
+ def visit_ClassDef(self, node: ast.ClassDef) -> Any:
169
+ # Only looking for top-level function calls
170
+ ...
171
+
172
+ def visit_FunctionDef(self, node: ast.FunctionDef):
173
+ # Only looking for top-level function calls
174
+ ...
175
+
176
+ def visit_For(self, node: ast.For):
177
+ # Only looking for top-level function calls
178
+ ...
179
+
180
+ def visit_AsyncFor(self, node: AsyncFor) -> Any:
181
+ # Only looking for top-level function calls
182
+ ...
183
+
184
+ def visit_If(self, node: ast.If):
185
+ # Only looking for top-level function calls
186
+ ...
187
+
188
+ def visit_While(self, node: ast.While):
189
+ # Only looking for top-level function calls
190
+ ...
191
+
192
+ def visit_AsyncWith(self, node: ast.AsyncWith):
193
+ # Only looking for top-level function calls
194
+ ...
195
+
196
+ def visit_Match(self, node: ast.Match):
197
+ # Only looking for top-level function calls
198
+ ...
199
+
200
+ function_call_collector = FunctionCallCollector()
201
+ function_call_collector.visit(tree)
202
+ return function_call_collector.function_calls
203
+
204
+
205
+ if __name__ == "__main__":
206
+ main()
trailhead/app.py ADDED
@@ -0,0 +1,163 @@
1
+ """Main module for the introductory programming web server."""
2
+
3
+ __author__ = "Kris Jordan <kris@cs.unc.edu>"
4
+ __copyright__ = "Copyright 2024"
5
+ __license__ = "MIT"
6
+
7
+ import asyncio
8
+ from contextlib import asynccontextmanager
9
+ from pathlib import Path
10
+
11
+ from fastapi import FastAPI, WebSocket, HTTPException
12
+ from fastapi.staticfiles import StaticFiles
13
+ from fastapi.responses import FileResponse
14
+ from starlette.websockets import WebSocketDisconnect, WebSocketState
15
+
16
+ from .web_socket_manager import WebSocketManager
17
+ from .file_observer import FileObserver
18
+ from .controller import web_socket_controller
19
+ from .web_socket_event import WebSocketEvent
20
+ from .async_python_subprocess import AsyncPythonSubprocess
21
+ from .analysis.inspect import analyze_module, Module
22
+ from .project import get_project_root, module_file
23
+ from .websocket_origin import (
24
+ WebSocketOriginMiddleware,
25
+ configured_websocket_origins,
26
+ )
27
+
28
+ web_socket_manager = WebSocketManager(web_socket_controller)
29
+ """Web Socket Manager handles connections and dispatches to the controller."""
30
+
31
+ PACKAGE_DIR = Path(__file__).resolve().parent
32
+ STATIC_DIR = PACKAGE_DIR / "static"
33
+
34
+
35
+ @asynccontextmanager
36
+ async def lifespan(app: FastAPI):
37
+ """
38
+ This function is called before the FastAPI web server begins, yields while
39
+ the web server is running, then shuts down depencies when halting. It is
40
+ responsible for starting and stopping the file observer and the web socket
41
+ manager.
42
+ """
43
+ # Validate configuration at startup rather than waiting for the first
44
+ # browser connection. Invalid values fail closed in the middleware too.
45
+ configured_websocket_origins()
46
+ file_observer = FileObserver(get_project_root(), web_socket_manager.notify)
47
+ try:
48
+ yield
49
+ finally:
50
+ file_observer.stop()
51
+ await asyncio.to_thread(file_observer.join, 5)
52
+ await web_socket_manager.stop()
53
+
54
+
55
+ app = FastAPI(lifespan=lifespan)
56
+ """The FastAPI web server instance."""
57
+ app.add_middleware(WebSocketOriginMiddleware)
58
+
59
+
60
+ @app.get("/api/module/{module}")
61
+ async def get_module(module: str) -> Module:
62
+ try:
63
+ path = module_file(module)
64
+ except ValueError:
65
+ raise HTTPException(status_code=404, detail="Module not found") from None
66
+ if not path.is_file():
67
+ raise HTTPException(status_code=404, detail="Module not found")
68
+ return analyze_module(str(path))
69
+
70
+
71
+ @app.get("/api/heartbeat")
72
+ async def get_heartbeat():
73
+ return "heartbeat"
74
+
75
+
76
+ async def _run_module_process(
77
+ module: str, client: WebSocket, wrapper: str = "trailhead.wrappers.module"
78
+ ) -> None:
79
+ """Run a module wrapper and relay its standard streams over a WebSocket."""
80
+
81
+ subprocess: AsyncPythonSubprocess | None = None
82
+ await client.accept()
83
+ try:
84
+ path = module_file(module)
85
+ except ValueError:
86
+ path = None
87
+ if path is None or not path.is_file():
88
+ await client.close(code=1008, reason="Module not found")
89
+ return
90
+
91
+ try:
92
+ subprocess = AsyncPythonSubprocess(module, client, wrapper)
93
+ pid = await subprocess.start()
94
+ response = WebSocketEvent(type="RUNNING", data={"pid": pid})
95
+ await client.send_text(response.model_dump_json())
96
+ while not subprocess.subprocess_exited():
97
+ try:
98
+ data = await asyncio.wait_for(client.receive_text(), timeout=0.1)
99
+ event = WebSocketEvent.model_validate_json(data)
100
+ match event.type:
101
+ case "KILL":
102
+ subprocess.kill()
103
+ case "STDIN":
104
+ await subprocess.write(event.data["data"])
105
+
106
+ except asyncio.TimeoutError:
107
+ # Expected while waiting for client input
108
+ pass
109
+ await subprocess.await_end()
110
+ except WebSocketDisconnect:
111
+ pass
112
+ finally:
113
+ if subprocess is not None and not subprocess.subprocess_exited():
114
+ subprocess.kill()
115
+
116
+ if client.client_state == WebSocketState.CONNECTED:
117
+ await client.close()
118
+
119
+
120
+ @app.websocket("/ws/{module}/run")
121
+ async def run_module(module: str, client: WebSocket):
122
+ """Run a Python module and relay its input and output."""
123
+
124
+ await _run_module_process(module, client)
125
+
126
+
127
+ @app.websocket("/ws/{module}/repl")
128
+ async def repl_module(module: str, client: WebSocket):
129
+ """Start an interactive REPL for a Python module."""
130
+
131
+ await _run_module_process(module, client, "trailhead.wrappers.repl")
132
+
133
+
134
+ @app.websocket("/ws/{module}/repl_gui")
135
+ async def repl_gui(module: str, client: WebSocket):
136
+ """Start the graphical REPL protocol for a Python module."""
137
+
138
+ await _run_module_process(module, client, "trailhead.wrappers.repl_gui")
139
+
140
+
141
+ @app.websocket("/ws")
142
+ async def websocket_endpoint(client: WebSocket):
143
+ """The FastAPI web socket endpoint dispatches out to Web Socket Manager."""
144
+ await web_socket_manager.accept(client)
145
+
146
+
147
+ if (STATIC_DIR / "assets").is_dir():
148
+ app.mount(
149
+ "/assets",
150
+ StaticFiles(directory=STATIC_DIR / "assets", html=True),
151
+ name="assets",
152
+ )
153
+
154
+
155
+ @app.get("/{full_path:path}")
156
+ async def read_index(full_path: str):
157
+ index = STATIC_DIR / "index.html"
158
+ if not index.is_file():
159
+ raise HTTPException(
160
+ status_code=404,
161
+ detail="Trailhead's web client has not been built or installed.",
162
+ )
163
+ return FileResponse(index)