clicodemode 0.6.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.
@@ -0,0 +1,46 @@
1
+ """Code Mode for Python CLIs.
2
+
3
+ Register the handlers your CLI already has as operations, then run small
4
+ JavaScript-like programs that call them. The language engine is the
5
+ ``clicodemode`` Go engine compiled to WebAssembly and executed by wasmtime;
6
+ Python never interprets the language.
7
+
8
+ >>> from clicodemode import CodeMode
9
+ >>> cm = CodeMode("1.0.0")
10
+ >>> @cm.operation("health.check", side_effects="none")
11
+ ... def health(args):
12
+ ... return {"ok": True}
13
+ >>> cm.run("export default async () => await ops.health.check({})").value
14
+ {'ok': True}
15
+ """
16
+
17
+ from .core import CodeMode, valid_name
18
+ from .errors import CodeModeError, EngineError, GuestCrashed, UsageError
19
+ from .types import (
20
+ Capabilities,
21
+ CompileResult,
22
+ Diagnostic,
23
+ Limits,
24
+ Operation,
25
+ Policy,
26
+ Result,
27
+ )
28
+
29
+ __version__ = "0.6.1"
30
+
31
+ __all__ = [
32
+ "CodeMode",
33
+ "Limits",
34
+ "Policy",
35
+ "Operation",
36
+ "Result",
37
+ "Diagnostic",
38
+ "CompileResult",
39
+ "Capabilities",
40
+ "CodeModeError",
41
+ "EngineError",
42
+ "GuestCrashed",
43
+ "UsageError",
44
+ "valid_name",
45
+ "__version__",
46
+ ]
Binary file
clicodemode/_guest.py ADDED
@@ -0,0 +1,366 @@
1
+ """Hosts the Go engine (compiled to WASI preview1) inside wasmtime.
2
+
3
+ The guest is a ``wasip1`` command that reads JSON lines on stdin and writes
4
+ JSON lines on stdout. Instead of real file descriptors this module implements
5
+ the ~20 WASI functions the Go runtime imports, with stdin/stdout as queues:
6
+ ``fd_read`` blocks the *guest worker thread* until the host sends a line and
7
+ ``fd_write`` hands finished lines to the host. There is no filesystem,
8
+ environment or network. This is the same idea as ``rust/src/guest.rs``.
9
+
10
+ One :class:`Guest` is one running engine instance on its own worker thread.
11
+ Stopping a runaway program uses wasmtime epoch interruption (a per-engine
12
+ counter), so every guest owns its own ``wasmtime.Engine``; the expensive part,
13
+ the compiled module, is shared process-wide through ``Module.serialize`` /
14
+ ``Module.deserialize`` (see :func:`load_module`).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import os
20
+ import queue
21
+ import struct
22
+ import threading
23
+ import time
24
+ from pathlib import Path
25
+ from typing import Any, Callable, List, Optional, Tuple, Union
26
+
27
+ import wasmtime
28
+ from wasmtime import Caller, Config, Engine, FuncType, Linker, Memory, Module, Store, Trap, ValType
29
+
30
+ WASM_PATH = Path(__file__).with_name("_codemode.wasm")
31
+
32
+ ESUCCESS = 0
33
+ EBADF = 8
34
+ EINVAL = 28
35
+ ENOSYS = 52
36
+
37
+ _i32 = ValType.i32
38
+ _i64 = ValType.i64
39
+
40
+
41
+ class GuestExit:
42
+ """Sentinel put on the output queue when the guest stops."""
43
+
44
+ def __init__(self, message: Optional[str]) -> None:
45
+ self.message = message
46
+
47
+
48
+ class _Exit(Exception):
49
+ def __init__(self, code: int) -> None:
50
+ super().__init__(f"proc_exit({code})")
51
+ self.code = code
52
+
53
+
54
+ def _config() -> Config:
55
+ cfg = Config()
56
+ cfg.epoch_interruption = True
57
+ return cfg
58
+
59
+
60
+ # --------------------------------------------------------------------------
61
+ # Module cache: compile once per process, deserialize per engine.
62
+ # --------------------------------------------------------------------------
63
+
64
+ _mod_lock = threading.Lock()
65
+ _serialized: Optional[bytes] = None
66
+ _compile_ms: float = 0.0
67
+
68
+
69
+ def load_module(engine: Engine) -> Tuple[Module, bool]:
70
+ """Return a module for ``engine`` and whether this call paid the compile.
71
+
72
+ The first call in the process compiles the wasm with Cranelift and keeps
73
+ the serialized artifact; later calls only deserialize it (an mmap-sized
74
+ cost), which is what makes creating many engines cheap.
75
+ """
76
+ global _serialized, _compile_ms
77
+ with _mod_lock:
78
+ if _serialized is None:
79
+ if not WASM_PATH.exists():
80
+ raise RuntimeError(
81
+ f"{WASM_PATH.name} is missing from the package; build it with "
82
+ "python/scripts/build_wasm.sh (a published wheel already contains it)"
83
+ )
84
+ t0 = time.perf_counter()
85
+ module = Module(engine, WASM_PATH.read_bytes())
86
+ _serialized = bytes(module.serialize())
87
+ _compile_ms = (time.perf_counter() - t0) * 1000
88
+ return module, True
89
+ blob = _serialized
90
+ return Module.deserialize(engine, blob), False
91
+
92
+
93
+ def last_compile_ms() -> float:
94
+ return _compile_ms
95
+
96
+
97
+ # --------------------------------------------------------------------------
98
+
99
+
100
+ class Guest:
101
+ """One engine instance running on a worker thread."""
102
+
103
+ def __init__(self) -> None:
104
+ self.inq: "queue.Queue[Optional[bytes]]" = queue.Queue()
105
+ self.outq: "queue.Queue[Union[bytes, GuestExit]]" = queue.Queue()
106
+ self._kill = threading.Event()
107
+ self._inbuf = b""
108
+ self._inpos = 0
109
+ self._outbuf = bytearray()
110
+ self._stderr = bytearray()
111
+ self._start = time.monotonic()
112
+ self._rng = int.from_bytes(os.urandom(8), "little") or 1
113
+ self.exit_message: Optional[str] = None
114
+ self.engine = Engine(_config())
115
+ self.compiled_cold = False
116
+ t0 = time.perf_counter()
117
+ self._module, self.compiled_cold = load_module(self.engine)
118
+ self.load_ms = (time.perf_counter() - t0) * 1000
119
+ self._ready = threading.Event()
120
+ old = threading.stack_size()
121
+ try:
122
+ threading.stack_size(16 << 20)
123
+ except (ValueError, RuntimeError): # pragma: no cover - platform limit
124
+ pass
125
+ try:
126
+ self._thread = threading.Thread(target=self._main, name="clicodemode-engine", daemon=True)
127
+ self._thread.start()
128
+ finally:
129
+ try:
130
+ threading.stack_size(old)
131
+ except (ValueError, RuntimeError): # pragma: no cover
132
+ pass
133
+
134
+ # ---- host-facing API -------------------------------------------------
135
+
136
+ def send(self, line: bytes) -> None:
137
+ self.inq.put(line if line.endswith(b"\n") else line + b"\n")
138
+
139
+ def alive(self) -> bool:
140
+ return self._thread.is_alive()
141
+
142
+ def stderr_tail(self) -> str:
143
+ return bytes(self._stderr[-2000:]).decode("utf-8", "replace")
144
+
145
+ def stop(self, hard: bool = False) -> None:
146
+ """End the guest. Soft: EOF on stdin. Hard: also interrupt running code."""
147
+ self._kill.set()
148
+ self.inq.put(None)
149
+ if hard:
150
+ self.engine.increment_epoch()
151
+ self._thread.join(timeout=10)
152
+
153
+ # ---- worker thread ---------------------------------------------------
154
+
155
+ def _main(self) -> None:
156
+ msg: Optional[str] = None
157
+ try:
158
+ store = Store(self.engine)
159
+ store.set_epoch_deadline(1) # first increment_epoch() traps the guest
160
+ linker = self._linker()
161
+ instance = linker.instantiate(store, self._module)
162
+ start = instance.exports(store)["_start"]
163
+ start(store) # type: ignore[operator]
164
+ except _Exit as e:
165
+ if e.code != 0:
166
+ msg = f"engine exited with status {e.code}"
167
+ except Trap as e:
168
+ if self._kill.is_set():
169
+ msg = "engine interrupted"
170
+ else:
171
+ msg = f"engine trapped: {str(e).splitlines()[0] if str(e) else 'trap'}"
172
+ except wasmtime.WasmtimeError as e:
173
+ c = getattr(e, "__cause__", None)
174
+ if isinstance(c, _Exit):
175
+ msg = None if c.code == 0 else f"engine exited with status {c.code}"
176
+ elif self._kill.is_set():
177
+ msg = "engine interrupted"
178
+ else:
179
+ msg = f"engine error: {e}"
180
+ except BaseException as e: # noqa: BLE001 - must not escape the thread
181
+ if self._kill.is_set():
182
+ msg = "engine interrupted"
183
+ else:
184
+ msg = f"engine error: {type(e).__name__}: {e}"
185
+ tail = self.stderr_tail().strip()
186
+ if msg and tail:
187
+ msg += f" (stderr: {tail[-400:]})"
188
+ self.exit_message = msg
189
+ self.outq.put(GuestExit(msg))
190
+
191
+ # ---- WASI preview1 ---------------------------------------------------
192
+
193
+ def _linker(self) -> Linker:
194
+ lk = Linker(self.engine)
195
+ M = "wasi_snapshot_preview1"
196
+
197
+ def fn(name: str, params: List[ValType], results: List[ValType], f: Callable[..., Any]) -> None:
198
+ lk.define_func(M, name, FuncType(params, results), f, access_caller=True)
199
+
200
+ def mem(c: Caller) -> Memory:
201
+ m = c.get("memory")
202
+ assert isinstance(m, Memory)
203
+ return m
204
+
205
+ def w32(c: Caller, p: int, v: int) -> None:
206
+ mem(c).write(c, struct.pack("<I", v & 0xFFFFFFFF), p)
207
+
208
+ def w64(c: Caller, p: int, v: int) -> None:
209
+ mem(c).write(c, struct.pack("<Q", v & 0xFFFFFFFFFFFFFFFF), p)
210
+
211
+ def iovs(c: Caller, p: int, n: int) -> List[Tuple[int, int]]:
212
+ raw = mem(c).read(c, p, p + 8 * n)
213
+ return [struct.unpack_from("<II", raw, 8 * i) for i in range(n)]
214
+
215
+ fn("sched_yield", [], [_i32()], lambda c: ESUCCESS)
216
+
217
+ def proc_exit(c: Caller, code: int) -> None:
218
+ raise _Exit(code)
219
+
220
+ fn("proc_exit", [_i32()], [], proc_exit)
221
+
222
+ def args_sizes_get(c: Caller, argc: int, size: int) -> int:
223
+ w32(c, argc, 1)
224
+ w32(c, size, 5)
225
+ return ESUCCESS
226
+
227
+ fn("args_sizes_get", [_i32(), _i32()], [_i32()], args_sizes_get)
228
+
229
+ def args_get(c: Caller, argv: int, buf: int) -> int:
230
+ w32(c, argv, buf)
231
+ mem(c).write(c, b"code\0", buf)
232
+ return ESUCCESS
233
+
234
+ fn("args_get", [_i32(), _i32()], [_i32()], args_get)
235
+
236
+ def environ_sizes_get(c: Caller, n: int, size: int) -> int:
237
+ w32(c, n, 0)
238
+ w32(c, size, 0)
239
+ return ESUCCESS
240
+
241
+ fn("environ_sizes_get", [_i32(), _i32()], [_i32()], environ_sizes_get)
242
+ fn("environ_get", [_i32(), _i32()], [_i32()], lambda c, a, b: ESUCCESS)
243
+
244
+ def clock_time_get(c: Caller, cid: int, _prec: int, out: int) -> int:
245
+ if cid == 0:
246
+ ns = time.time_ns()
247
+ elif 1 <= cid <= 3:
248
+ ns = int((time.monotonic() - self._start) * 1e9) + 1_000_000_000
249
+ else:
250
+ return EINVAL
251
+ w64(c, out, ns)
252
+ return ESUCCESS
253
+
254
+ fn("clock_time_get", [_i32(), _i64(), _i32()], [_i32()], clock_time_get)
255
+
256
+ def random_get(c: Caller, buf: int, n: int) -> int:
257
+ mem(c).write(c, os.urandom(n), buf)
258
+ return ESUCCESS
259
+
260
+ fn("random_get", [_i32(), _i32()], [_i32()], random_get)
261
+
262
+ def fd_write(c: Caller, fd: int, iov: int, n: int, nw: int) -> int:
263
+ if fd not in (1, 2):
264
+ return EBADF
265
+ m = mem(c)
266
+ total = 0
267
+ for ptr, ln in iovs(c, iov, n):
268
+ chunk = m.read(c, ptr, ptr + ln)
269
+ total += ln
270
+ if fd == 2:
271
+ self._stderr += chunk
272
+ if len(self._stderr) > 8000:
273
+ del self._stderr[:-4000]
274
+ else:
275
+ self._outbuf += chunk
276
+ while True:
277
+ i = self._outbuf.find(b"\n")
278
+ if i < 0:
279
+ break
280
+ line = bytes(self._outbuf[: i + 1])
281
+ del self._outbuf[: i + 1]
282
+ self.outq.put(line)
283
+ w32(c, nw, total)
284
+ return ESUCCESS
285
+
286
+ fn("fd_write", [_i32()] * 4, [_i32()], fd_write)
287
+
288
+ def fd_read(c: Caller, fd: int, iov: int, n: int, nr: int) -> int:
289
+ if fd != 0:
290
+ return EBADF
291
+ if self._inpos >= len(self._inbuf):
292
+ b = self.inq.get()
293
+ if b is None: # host went away: EOF
294
+ w32(c, nr, 0)
295
+ return ESUCCESS
296
+ self._inbuf, self._inpos = b, 0
297
+ m = mem(c)
298
+ total = 0
299
+ for ptr, ln in iovs(c, iov, n):
300
+ take = min(ln, len(self._inbuf) - self._inpos)
301
+ if take:
302
+ m.write(c, self._inbuf[self._inpos : self._inpos + take], ptr)
303
+ self._inpos += take
304
+ total += take
305
+ w32(c, nr, total)
306
+ return ESUCCESS
307
+
308
+ fn("fd_read", [_i32()] * 4, [_i32()], fd_read)
309
+ fn("fd_close", [_i32()], [_i32()], lambda c, fd: ESUCCESS)
310
+
311
+ def fd_fdstat_get(c: Caller, fd: int, out: int) -> int:
312
+ if not 0 <= fd <= 2:
313
+ return EBADF
314
+ mem(c).write(c, bytes([2]) + bytes(23), out) # character device
315
+ return ESUCCESS
316
+
317
+ fn("fd_fdstat_get", [_i32(), _i32()], [_i32()], fd_fdstat_get)
318
+ fn("fd_fdstat_set_flags", [_i32(), _i32()], [_i32()], lambda c, a, b: ENOSYS)
319
+ fn("fd_filestat_get", [_i32(), _i32()], [_i32()], lambda c, a, b: EBADF)
320
+ fn("fd_prestat_get", [_i32(), _i32()], [_i32()], lambda c, a, b: EBADF)
321
+ fn("fd_prestat_dir_name", [_i32()] * 3, [_i32()], lambda c, a, b, d: EBADF)
322
+ fn("path_filestat_get", [_i32()] * 5, [_i32()], lambda c, a, b, d, e, f: ENOSYS)
323
+ fn("path_readlink", [_i32()] * 6, [_i32()], lambda c, a, b, d, e, f, g: ENOSYS)
324
+ fn(
325
+ "path_open",
326
+ [_i32(), _i32(), _i32(), _i32(), _i32(), _i64(), _i64(), _i32(), _i32()],
327
+ [_i32()],
328
+ lambda c, a, b, d, e, f, g, h, i, j: ENOSYS,
329
+ )
330
+
331
+ def poll_oneoff(c: Caller, subs: int, events: int, n: int, out: int) -> int:
332
+ # only timers are used (time.Sleep, scheduler idle)
333
+ m = mem(c)
334
+ raw = m.read(c, subs, subs + 48 * n)
335
+ now_real = time.time_ns()
336
+ now_mono = int((time.monotonic() - self._start) * 1e9) + 1_000_000_000
337
+ wait: Optional[int] = None
338
+ first: Optional[int] = None
339
+ for i in range(n):
340
+ o = 48 * i
341
+ if raw[o + 8] == 0:
342
+ cid = struct.unpack_from("<I", raw, o + 16)[0]
343
+ timeout = struct.unpack_from("<Q", raw, o + 24)[0]
344
+ absolute = struct.unpack_from("<I", raw, o + 40)[0] & 1
345
+ rel = max(0, timeout - (now_real if cid == 0 else now_mono)) if absolute else timeout
346
+ if wait is None or rel < wait:
347
+ wait, first = rel, i
348
+ if first is None:
349
+ return ENOSYS
350
+ self._kill.wait((wait or 0) / 1e9) # wakes early when the guest is being stopped
351
+ ud = struct.unpack_from("<Q", raw, 48 * first)[0]
352
+ m.write(c, struct.pack("<Q", ud) + bytes(24), events) # clock event, errno 0
353
+ w32(c, out, 1)
354
+ return ESUCCESS
355
+
356
+ fn("poll_oneoff", [_i32()] * 4, [_i32()], poll_oneoff)
357
+ return lk
358
+
359
+
360
+ def preload() -> None: # pragma: no cover - convenience for benchmarks
361
+ """Compile the module now so the first engine does not pay for it."""
362
+ e = Engine(_config())
363
+ load_module(e)
364
+
365
+
366
+ __all__ = ["Guest", "GuestExit", "WASM_PATH", "load_module", "preload", "last_compile_ms"]