juart-cli 0.1.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.
juart/commands.py ADDED
@@ -0,0 +1,127 @@
1
+ """Pure command parsing and completion, with no transport or shell side effects."""
2
+
3
+ import re
4
+ from dataclasses import dataclass
5
+ from os.path import commonprefix
6
+
7
+ MAX_PAYLOAD = 4096
8
+ ALIASES = {
9
+ "c": "connect",
10
+ "d": "disconnect",
11
+ "r": "reconnect",
12
+ "q": "quit",
13
+ "s": "status",
14
+ "i": "info",
15
+ "h": "help",
16
+ }
17
+ COMMANDS = (
18
+ "!",
19
+ "buffer",
20
+ "connect",
21
+ "direct",
22
+ "disconnect",
23
+ "help",
24
+ "hex",
25
+ "info",
26
+ "log",
27
+ "quit",
28
+ "reconnect",
29
+ "status",
30
+ "view",
31
+ )
32
+ NO_ARGUMENTS = frozenset(COMMANDS) - {"!", "hex", "log", "view"}
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class CommandResult:
37
+ ok: bool = True
38
+ exit_requested: bool = False
39
+ shell_requested: bool = False
40
+ shell_command: str | None = None
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class ParsedCommand:
45
+ name: str
46
+ argument: str = ""
47
+
48
+
49
+ def parse_command(line: str) -> ParsedCommand:
50
+ """Keep shell arguments verbatim, including quoting and Windows backslashes."""
51
+ if any(character in line for character in "\x00\r\n"):
52
+ raise ValueError("Commands must be a single line without NUL.")
53
+ text = line.lstrip()
54
+ if text.startswith(":"):
55
+ text = text[1:].lstrip()
56
+ if not text:
57
+ return ParsedCommand("")
58
+ if text.startswith("!"):
59
+ return ParsedCommand("!", text[1:].lstrip())
60
+ parts = text.strip().split(None, 1)
61
+ name = ALIASES.get(parts[0], parts[0])
62
+ if name not in COMMANDS:
63
+ raise ValueError("Unknown command. Use :help for available commands.")
64
+ argument = parts[1] if len(parts) == 2 else ""
65
+ if name in NO_ARGUMENTS and argument:
66
+ raise ValueError(f":{name} does not accept arguments.")
67
+ return ParsedCommand(name, argument)
68
+
69
+
70
+ def parse_hex(argument: str) -> bytes:
71
+ text = argument.strip(" ")
72
+ if not re.fullmatch(r"[0-9a-fA-F]{2}(?: +[0-9a-fA-F]{2})*", text):
73
+ raise ValueError("HEX requires 1–4096 space-separated two-digit byte pairs.")
74
+ pairs = text.split()
75
+ if len(pairs) > MAX_PAYLOAD:
76
+ raise ValueError("HEX payload exceeds 4096 bytes.")
77
+ return bytes(int(pair, 16) for pair in pairs)
78
+
79
+
80
+ def parse_log(argument: str) -> tuple[str, str | None]:
81
+ parts = argument.split(None, 1)
82
+ if parts == ["stop"]:
83
+ return "stop", None
84
+ if len(parts) != 2 or parts[0] != "start":
85
+ raise ValueError("Use :log start <path> or :log stop.")
86
+ path = parts[1].strip()
87
+ if path.startswith(("'", '"')):
88
+ quote = path[0]
89
+ end = path.find(quote, 1)
90
+ if end == -1 or path[end + 1 :].strip():
91
+ raise ValueError("Log start requires exactly one quoted or unquoted path.")
92
+ path = path[1:end]
93
+ elif any(character.isspace() or character in "\"'" for character in path):
94
+ raise ValueError("Quote log paths containing spaces.")
95
+ if not path or any(character in path for character in "\x00\r\n"):
96
+ raise ValueError("Log path must not be empty or contain control separators.")
97
+ return "start", path
98
+
99
+
100
+ def completion_candidates(text: str) -> list[str]:
101
+ """Return complete command prefixes, not filesystem or history contents."""
102
+ if not text or not any(character.isspace() for character in text):
103
+ names = (*COMMANDS, *ALIASES)
104
+ return sorted(name for name in names if name.startswith(text))
105
+ parts = text.split()
106
+ name = ALIASES.get(parts[0], parts[0]) if parts else ""
107
+ if name not in {"view", "log"}:
108
+ return []
109
+ prefix = parts[1] if len(parts) == 2 and not text[-1].isspace() else ""
110
+ if len(parts) > 2 or (len(parts) == 2 and text[-1].isspace()):
111
+ return []
112
+ choices = ("text", "hex") if name == "view" else ("start", "stop")
113
+ return [f"{parts[0]} {choice}" for choice in choices if choice.startswith(prefix)]
114
+
115
+
116
+ def complete_command(text: str) -> tuple[str, list[str]]:
117
+ candidates = completion_candidates(text)
118
+ if not candidates:
119
+ return text, []
120
+ completed = commonprefix(candidates)
121
+ if len(candidates) == 1 and " " not in completed:
122
+ completed += " "
123
+ return completed, candidates
124
+
125
+
126
+ def history_allowed(command: ParsedCommand) -> bool:
127
+ return bool(command.name) and command.name not in {"!", "hex", "log"}
juart/logging.py ADDED
@@ -0,0 +1,314 @@
1
+ """Opt-in structured logging with bounded memory and isolated filesystem I/O."""
2
+
3
+ import asyncio
4
+ import json
5
+ import math
6
+ import re
7
+ import sys
8
+ from collections.abc import Callable
9
+ from dataclasses import asdict, is_dataclass
10
+ from datetime import datetime, timezone
11
+ from pathlib import Path
12
+
13
+ _WORKER_PATH = Path(__file__).with_name("_log_worker.py")
14
+ _EVENT_FIELDS = {
15
+ "state": {"state", "code"},
16
+ "tx": {"data"},
17
+ "rx": {"data"},
18
+ "send_result": {"requested", "accepted", "uncertain"},
19
+ }
20
+
21
+
22
+ class JsonLogger:
23
+ """A session-scoped sequence counter and an explicitly enabled JSONL sink.
24
+
25
+ ``emit`` never waits for a pipe or filesystem. Outstanding records, including
26
+ records already in the child pipe but not acknowledged, count toward the
27
+ queue bound. Only the worker touches the selected path.
28
+ """
29
+
30
+ def __init__(
31
+ self,
32
+ *,
33
+ on_error: Callable[[str], None] | None = None,
34
+ max_queue: int = 256,
35
+ shutdown_timeout: float = 2.0,
36
+ ):
37
+ if isinstance(max_queue, bool) or not isinstance(max_queue, int) or max_queue < 1:
38
+ raise ValueError("max_queue must be a positive integer")
39
+ if not math.isfinite(shutdown_timeout) or shutdown_timeout <= 0:
40
+ raise ValueError("shutdown_timeout must be finite and positive")
41
+ self.active = False
42
+ self.last_written = 0
43
+ self.error: str | None = None
44
+ self._on_error = on_error
45
+ self._max_queue = max_queue
46
+ self._timeout = shutdown_timeout
47
+ self._sequence = 0
48
+ self._pending: set[int] = set()
49
+ self._dropped = 0
50
+ self._process = None
51
+ self._queue = None
52
+ self._writer = None
53
+ self._reader = None
54
+ self._cleanup = None
55
+ self._lock = asyncio.Lock()
56
+ self._closed_ack = False
57
+ self._result = {"last_written": 0, "unwritten": 0, "error": None}
58
+
59
+ def _fail(self, message: str) -> None:
60
+ self.active = False
61
+ if self.error is None:
62
+ self.error = message
63
+ elif message not in self.error:
64
+ self.error += "; " + message
65
+ if self._on_error is not None:
66
+ try:
67
+ self._on_error(f"{message}; last_written={self.last_written}")
68
+ except Exception:
69
+ # Diagnostics must not make communication unavailable either.
70
+ pass
71
+ if self._process is not None and (self._cleanup is None or self._cleanup.done()):
72
+ self._cleanup = asyncio.create_task(self._cleanup_process(self._process))
73
+
74
+ async def _cleanup_process(self, process) -> None:
75
+ async with self._lock:
76
+ if self._process is process:
77
+ await self._stop_locked()
78
+
79
+ async def start(self, path: str | Path) -> None:
80
+ """Exclusively create a new log, or raise without disturbing an active log."""
81
+ async with self._lock:
82
+ if self.active:
83
+ raise ValueError("logging is already active")
84
+ if self._process is not None:
85
+ await self._stop_locked()
86
+ if not isinstance(path, (str, Path)) or not str(path) or "\x00" in str(path):
87
+ self.error = None
88
+ self._fail("log startup failed: invalid path")
89
+ self._result = {
90
+ "last_written": self.last_written,
91
+ "unwritten": 0,
92
+ "error": self.error,
93
+ }
94
+ raise ValueError("log path must be a nonempty path without NUL characters")
95
+ self.error = None
96
+ self._pending.clear()
97
+ self._dropped = 0
98
+ self._closed_ack = False
99
+ self._cleanup = None
100
+ self._queue = asyncio.Queue(maxsize=self._max_queue)
101
+ try:
102
+ async with asyncio.timeout(self._timeout):
103
+ self._process = await asyncio.create_subprocess_exec(
104
+ sys.executable,
105
+ "-u",
106
+ str(_WORKER_PATH),
107
+ str(path),
108
+ stdin=asyncio.subprocess.PIPE,
109
+ stdout=asyncio.subprocess.PIPE,
110
+ stderr=asyncio.subprocess.DEVNULL,
111
+ )
112
+ line = await self._process.stdout.readline()
113
+ if not line:
114
+ raise OSError("log worker exited before opening the file")
115
+ reply = json.loads(line)
116
+ if reply.get("kind") == "startup_error":
117
+ if reply.get("invalid"):
118
+ raise ValueError(reply["message"])
119
+ raise OSError(reply.get("errno"), reply["message"], str(path))
120
+ if reply.get("kind") != "ready":
121
+ raise OSError("invalid log worker startup acknowledgement")
122
+ except (OSError, ValueError, TimeoutError) as exc:
123
+ message = (
124
+ "log startup timed out"
125
+ if isinstance(exc, TimeoutError)
126
+ else f"log startup failed: {exc}"
127
+ )
128
+ self._fail(message)
129
+ await self._dispose()
130
+ self._result = {
131
+ "last_written": self.last_written,
132
+ "unwritten": 0,
133
+ "error": self.error,
134
+ }
135
+ if isinstance(exc, TimeoutError):
136
+ raise OSError("log startup timed out") from exc
137
+ raise
138
+ except BaseException:
139
+ await self._dispose()
140
+ raise
141
+ self.active = True
142
+ self._writer = asyncio.create_task(self._write_records())
143
+ self._reader = asyncio.create_task(self._read_acks())
144
+
145
+ def _record(self, event_type: str, fields: dict) -> dict:
146
+ if event_type not in _EVENT_FIELDS:
147
+ raise ValueError("unsupported log event")
148
+ allowed = _EVENT_FIELDS[event_type] | {"driver", "target"}
149
+ if fields.keys() - allowed:
150
+ raise ValueError("unsupported log fields")
151
+ result = {}
152
+ for key, value in fields.items():
153
+ if key == "target":
154
+ if is_dataclass(value) and not isinstance(value, type):
155
+ value = asdict(value)
156
+ if not isinstance(value, dict) or value.keys() - {"cable", "device", "instance"}:
157
+ raise ValueError("invalid log target")
158
+ value = dict(value)
159
+ if value.get("cable") is not None and not isinstance(value["cable"], str):
160
+ raise ValueError("invalid target cable")
161
+ for name in ("device", "instance"):
162
+ if value.get(name) is not None and (
163
+ type(value[name]) is not int or value[name] < 0
164
+ ):
165
+ raise ValueError("invalid target index")
166
+ elif key in {"driver", "state", "code"}:
167
+ if not isinstance(value, str):
168
+ raise ValueError(f"invalid log {key}")
169
+ if (
170
+ key in {"state", "code"}
171
+ and re.fullmatch(r"[A-Za-z][A-Za-z0-9_.:-]{0,127}", value) is None
172
+ ):
173
+ raise ValueError(f"log {key} must be a structured identifier")
174
+ elif key == "data":
175
+ if (
176
+ not isinstance(value, str)
177
+ or len(value) % 2
178
+ or any(ch not in "0123456789abcdefABCDEF" for ch in value)
179
+ ):
180
+ raise ValueError("log data must be hex byte pairs")
181
+ value = value.lower()
182
+ elif key in {"requested", "accepted"}:
183
+ if type(value) is not int or value < 0:
184
+ raise ValueError("log counts must be nonnegative integers")
185
+ elif key == "uncertain" and not isinstance(value, bool):
186
+ raise ValueError("log uncertainty must be boolean")
187
+ result[key] = value
188
+ if "accepted" in result and "requested" in result:
189
+ if result["accepted"] > result["requested"]:
190
+ raise ValueError("accepted count exceeds requested count")
191
+ return result
192
+
193
+ def emit(self, event_type: str, **fields) -> None:
194
+ """Accept only structured events; never block or expose caller exceptions."""
195
+ if not self.active:
196
+ return
197
+ try:
198
+ record = self._record(event_type, fields)
199
+ except (ValueError, TypeError) as exc:
200
+ self._fail(f"invalid log record: {exc}")
201
+ return
202
+ self._sequence += 1
203
+ if len(self._pending) >= self._max_queue:
204
+ self._dropped += 1
205
+ self._fail("log queue overflow")
206
+ return
207
+ record.update(
208
+ timestamp=datetime.now(timezone.utc)
209
+ .isoformat(timespec="microseconds")
210
+ .replace("+00:00", "Z"),
211
+ sequence=self._sequence,
212
+ event=event_type,
213
+ )
214
+ self._pending.add(self._sequence)
215
+ self._queue.put_nowait(record)
216
+
217
+ async def _write_records(self) -> None:
218
+ try:
219
+ while True:
220
+ record = await self._queue.get()
221
+ message = (
222
+ {"kind": "stop"} if record is None else {"kind": "record", "record": record}
223
+ )
224
+ self._process.stdin.write(
225
+ (json.dumps(message, ensure_ascii=True, separators=(",", ":")) + "\n").encode()
226
+ )
227
+ await self._process.stdin.drain()
228
+ if record is None:
229
+ return
230
+ except (OSError, ValueError, RuntimeError) as exc:
231
+ self._fail(f"log pipe write failed: {exc}")
232
+
233
+ async def _read_acks(self) -> None:
234
+ try:
235
+ while line := await self._process.stdout.readline():
236
+ message = json.loads(line)
237
+ kind = message.get("kind")
238
+ if kind == "written":
239
+ sequence = message.get("sequence")
240
+ if sequence not in self._pending:
241
+ raise ValueError("invalid log sequence acknowledgement")
242
+ self._pending.remove(sequence)
243
+ self.last_written = sequence
244
+ elif kind == "closed":
245
+ self._closed_ack = True
246
+ elif kind == "error":
247
+ self._fail(f"log write failed: {message.get('message', 'worker error')}")
248
+ else:
249
+ raise ValueError("invalid log worker acknowledgement")
250
+ if not self._closed_ack and self.error is None:
251
+ self._fail("log worker exited without closing the file")
252
+ except (OSError, ValueError, TypeError) as exc:
253
+ self._fail(f"log acknowledgement failed: {exc}")
254
+
255
+ async def _dispose(self) -> None:
256
+ process = self._process
257
+ if process is not None and process.returncode is None:
258
+ try:
259
+ process.kill()
260
+ except ProcessLookupError:
261
+ pass
262
+ tasks = [task for task in (self._writer, self._reader) if task is not None]
263
+ for task in tasks:
264
+ if not task.done():
265
+ task.cancel()
266
+ if tasks:
267
+ await asyncio.gather(*tasks, return_exceptions=True)
268
+ if process is not None:
269
+ if process.stdin is not None:
270
+ process.stdin.close()
271
+ try:
272
+ await asyncio.wait_for(process.wait(), timeout=0.5)
273
+ except TimeoutError:
274
+ self._fail("log worker could not be reaped before deadline")
275
+ self._process = None
276
+ self._writer = None
277
+ self._reader = None
278
+ self._queue = None
279
+
280
+ async def _stop_locked(self) -> dict:
281
+ self.active = False
282
+ if self._process is None:
283
+ return dict(self._result)
284
+ try:
285
+ async with asyncio.timeout(self._timeout):
286
+ await self._queue.put(None)
287
+ await self._writer
288
+ await self._process.wait()
289
+ await self._reader
290
+ if not self._closed_ack and self.error is None:
291
+ self._fail("log worker did not acknowledge file close")
292
+ except TimeoutError:
293
+ self._fail("log shutdown timed out")
294
+ finally:
295
+ await self._dispose()
296
+ self._result = {
297
+ "last_written": self.last_written,
298
+ "unwritten": len(self._pending) + self._dropped,
299
+ "error": self.error,
300
+ }
301
+ if self._result["unwritten"] and self._on_error is not None:
302
+ try:
303
+ self._on_error(
304
+ f"log stopped; last_written={self.last_written}; "
305
+ f"unwritten={self._result['unwritten']}"
306
+ )
307
+ except Exception:
308
+ pass
309
+ return dict(self._result)
310
+
311
+ async def stop(self) -> dict:
312
+ """Flush and close within a deadline, killing/reaping a stalled worker."""
313
+ async with self._lock:
314
+ return await self._stop_locked()