antweft 0.1.1__py3-none-win_arm64.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.
antweft/__init__.py ADDED
@@ -0,0 +1,254 @@
1
+ """Antweft's Python runtime: the exceptions that native code raises in Python, and
2
+ ``export`` for Python functions native code calls.
3
+
4
+ Generated extension modules import this package and raise these classes, so user code can
5
+ catch them by name, e.g. ``except antweft.RustPanic``.
6
+ """
7
+
8
+ __version__ = "0.1.1"
9
+ __all__ = ["AntweftError", "GoPanic", "NativeError", "RustPanic", "export", "library"]
10
+
11
+ def _operators(cls, names):
12
+ """Make a native class's operator methods (``__eq__``, ``__add__``, ...) Python's operators.
13
+
14
+ Called by generated modules. Each takes another object of the same class; with anything
15
+ else it returns ``NotImplemented``, so ``obj == 5`` is False rather than an error.
16
+ """
17
+ for name in names.split():
18
+ method = cls.__dict__[name]
19
+
20
+ def op(self, other, _method=method):
21
+ if not isinstance(other, type(self)):
22
+ return NotImplemented
23
+ return _method(self, other)
24
+
25
+ op.__name__ = name
26
+ op.__doc__ = method.__doc__
27
+ setattr(cls, name, op)
28
+ if "__eq__" in names.split():
29
+ cls.__hash__ = None # equal objects must hash alike; value equality isn't identity
30
+
31
+
32
+ def _make_async(module, names):
33
+ """Make a module's Rust ``async fn``s awaitable. Called by generated modules.
34
+
35
+ Each becomes an ``async def`` that runs the native call (which drives the future to
36
+ completion, with the GIL released) on a worker thread, so the event loop keeps running.
37
+ """
38
+ import asyncio
39
+ import functools
40
+
41
+ for name in names.split():
42
+ blocking = getattr(module, name)
43
+
44
+ @functools.wraps(blocking)
45
+ async def call(*args, _blocking=blocking, **kwargs):
46
+ return await asyncio.to_thread(_blocking, *args, **kwargs)
47
+
48
+ setattr(module, name, call)
49
+
50
+
51
+ def _codec(cls, name, spec):
52
+ """Give a C++ class's method ``list[str]``/``dict`` arguments and results. Called by
53
+ generated modules.
54
+
55
+ They cross as a byte payload the generated C++ reads and writes: counts and lengths as
56
+ little-endian u64, integers as i64, floats as f64, bools as one byte. ``spec``: the Python
57
+ argument positions and the result with their kinds (``ls``, or ``m`` + key + value letters).
58
+ """
59
+ import struct
60
+
61
+ def enc(kind, v):
62
+ if kind == "s":
63
+ b = v.encode() if isinstance(v, str) else None
64
+ if b is None:
65
+ raise TypeError(f"{cls.__name__}.{name}() expects str keys and values here, not {type(v).__name__}")
66
+ return struct.pack("<Q", len(b)) + b
67
+ if kind == "i":
68
+ return struct.pack("<q", int(v))
69
+ if kind == "f":
70
+ return struct.pack("<d", float(v))
71
+ return b"\x01" if v else b"\x00"
72
+
73
+ def encode(kind, value):
74
+ if kind == "ls":
75
+ items = list(value)
76
+ return struct.pack("<Q", len(items)) + b"".join(enc("s", x) for x in items)
77
+ if not isinstance(value, dict):
78
+ raise TypeError(f"{cls.__name__}.{name}() expects a dict, not {type(value).__name__}")
79
+ return struct.pack("<Q", len(value)) + b"".join(enc(kind[1], k) + enc(kind[2], v) for k, v in value.items())
80
+
81
+ def decode(kind, data):
82
+ view = memoryview(data)
83
+ at = 8
84
+ (n,) = struct.unpack_from("<Q", view, 0)
85
+
86
+ def dec(k):
87
+ nonlocal at
88
+ if k == "s":
89
+ (size,) = struct.unpack_from("<Q", view, at)
90
+ text = bytes(view[at + 8 : at + 8 + size]).decode()
91
+ at += 8 + size
92
+ return text
93
+ if k == "i":
94
+ (x,) = struct.unpack_from("<q", view, at)
95
+ elif k == "f":
96
+ (x,) = struct.unpack_from("<d", view, at)
97
+ else:
98
+ x = view[at] != 0
99
+ at += 1
100
+ return x
101
+ at += 8
102
+ return x
103
+
104
+ if kind == "ls":
105
+ return [dec("s") for _ in range(n)]
106
+ out = {}
107
+ for _ in range(n):
108
+ key = dec(kind[1])
109
+ out[key] = dec(kind[2])
110
+ return out
111
+
112
+ parts = dict(p.split(":") for p in spec.split())
113
+ raw = cls.__dict__[name]
114
+ is_static = isinstance(raw, staticmethod)
115
+ target = raw.__func__ if is_static else raw
116
+ by_position = {int(k): v for k, v in parts.items() if k != "ret"}
117
+ result = parts.get("ret")
118
+
119
+ def call(*args):
120
+ args = list(args)
121
+ shift = 0 if is_static else 1 # `self` comes first in a method
122
+ for i, kind in by_position.items():
123
+ if i + shift < len(args):
124
+ args[i + shift] = encode(kind, args[i + shift])
125
+ value = target(*args)
126
+ return decode(result, value) if result is not None else value
127
+
128
+ call.__name__ = name
129
+ call.__doc__ = getattr(target, "__doc__", None)
130
+ setattr(cls, name, staticmethod(call) if is_static else call)
131
+
132
+
133
+ # Functions marked @export, by name, for the native side to find.
134
+ _exports = {}
135
+
136
+
137
+ def export(fn):
138
+ """Make ``fn`` callable from Rust, C and Go by its name.
139
+
140
+ The native side declares it as a C function (``extern "C" { fn scale(x: f64) -> f64; }``, a C
141
+ prototype, a cgo prototype) and calls it, from any thread. Parameters and results are
142
+ ``int``, ``float``, ``bool``, ``str``, ``bytes``, ``list[int]`` and ``list[float]``; Antweft
143
+ reads the annotations when it builds. An ``async def`` runs to completion. The
144
+ module defining it must be imported before native code calls it. An exception it raises is
145
+ reported as unraisable, and the native caller gets zero (or NULL).
146
+ """
147
+ import inspect
148
+
149
+ if inspect.iscoroutinefunction(fn):
150
+ # Native code waits for the result: the coroutine runs to completion, in a fresh event
151
+ # loop (on another thread when this one is already running a loop).
152
+ def run(*args):
153
+ import asyncio
154
+ import threading
155
+
156
+ try:
157
+ asyncio.get_running_loop()
158
+ except RuntimeError:
159
+ return asyncio.run(fn(*args))
160
+ box = {}
161
+
162
+ def worker():
163
+ try:
164
+ box["value"] = asyncio.run(fn(*args))
165
+ except BaseException as e: # noqa: BLE001 - re-raised below, in the caller's thread
166
+ box["error"] = e
167
+
168
+ t = threading.Thread(target=worker)
169
+ t.start()
170
+ t.join()
171
+ if "error" in box:
172
+ raise box["error"]
173
+ return box["value"]
174
+
175
+ _exports[fn.__name__] = run
176
+ else:
177
+ _exports[fn.__name__] = fn
178
+ return fn
179
+
180
+
181
+ def library(name):
182
+ """The path of a C-ABI library Antweft built, for ``ctypes.CDLL``.
183
+
184
+ ``name`` is a library name (``"core_ring"`` for ``core_ring.c`` or ``libcore_ring.c``) or a
185
+ module name (``"libanalyzer"`` for ``libanalyzer.rs``). A Go module's name gives the one
186
+ shared Go library, which holds every ``//export`` of the project's Go files.
187
+ """
188
+ import json
189
+ import os
190
+
191
+ pkg = os.path.dirname(os.path.abspath(__file__))
192
+ here = os.path.dirname(pkg)
193
+ # `antweft run` writes one map; each installed project wheel adds its own under _libraries/.
194
+ maps = [os.path.join(pkg, "_libraries.json")]
195
+ folder = os.path.join(pkg, "_libraries")
196
+ if os.path.isdir(folder):
197
+ maps += [os.path.join(folder, f) for f in sorted(os.listdir(folder)) if f.endswith(".json")]
198
+ known = {}
199
+ for path in maps:
200
+ try:
201
+ with open(path) as f:
202
+ known.update(json.load(f))
203
+ except (OSError, ValueError):
204
+ pass
205
+ if name in known:
206
+ # Always a file next to the modules: a map can't point anywhere else.
207
+ return os.path.join(here, os.path.basename(known[name]))
208
+ raise LookupError(
209
+ f"Antweft built no library called {name!r}"
210
+ + (f"; it built: {', '.join(sorted(known))}" if known else "")
211
+ )
212
+
213
+
214
+ class AntweftError(Exception):
215
+ """Base class for every error that comes from Antweft or from native code."""
216
+
217
+
218
+ class NativeError(AntweftError):
219
+ """Native code reported an error: a Rust ``Err(e)``, a Go ``error``, or a nonzero C status code."""
220
+
221
+
222
+ class RustPanic(AntweftError):
223
+ """Rust code panicked. The panic was caught at the boundary and never crossed it.
224
+
225
+ ``file`` and ``line`` say where in the user's Rust file the panic happened, when known.
226
+ """
227
+
228
+ def __init__(self, message, file=None, line=None):
229
+ super().__init__(message)
230
+ self.message = message
231
+ self.file = file
232
+ self.line = line
233
+
234
+ def __str__(self):
235
+ where = f" ({self.file}:{self.line})" if self.file and self.line else ""
236
+ return f"{self.message}{where}"
237
+
238
+
239
+ class GoPanic(AntweftError):
240
+ """Go code panicked. The panic was recovered at the boundary and never crossed it.
241
+
242
+ ``file`` and ``line`` say where in the user's Go file it happened, when known. A sibling of
243
+ ``RustPanic``, not a kind of it: ``except antweft.RustPanic`` doesn't catch Go panics.
244
+ """
245
+
246
+ def __init__(self, message, file=None, line=None):
247
+ super().__init__(message)
248
+ self.message = message
249
+ self.file = file
250
+ self.line = line
251
+
252
+ def __str__(self):
253
+ where = f" ({self.file}:{self.line})" if self.file and self.line else ""
254
+ return f"{self.message}{where}"
antweft/_wasm.py ADDED
@@ -0,0 +1,273 @@
1
+ """Calls a Wasm component Antweft built: the runtime half of a module from `antweft run --wasm`.
2
+
3
+ The generated module describes each function's types; this converts Python values to wasmtime's
4
+ and back, raises a Rust `Err` as ``antweft.NativeError`` and a trap (a Rust panic) as
5
+ ``antweft.RustPanic``, and starts a fresh instance after a trap, which leaves the old one unusable
6
+ Calls are serialised: a wasmtime store isn't safe to use from two threads.
7
+ """
8
+
9
+ import os
10
+ import sys
11
+ import threading
12
+
13
+ from . import NativeError, RustPanic
14
+
15
+
16
+ def _wasmtime():
17
+ """wasmtime, from the program's Python or from the copy Antweft installed into its cache."""
18
+ try:
19
+ import wasmtime
20
+ import wasmtime.component
21
+ except ImportError:
22
+ extra = os.environ.get("ANTWEFT_WASMTIME_PATH")
23
+ if not extra:
24
+ raise ImportError(
25
+ "this module was built for Wasm and needs the `wasmtime` package; "
26
+ "run it with `antweft run --wasm`, or `pip install wasmtime`"
27
+ ) from None
28
+ sys.path.insert(0, extra)
29
+ import wasmtime
30
+ import wasmtime.component
31
+ return wasmtime
32
+
33
+
34
+ class Component:
35
+ def __init__(self, module_file, wasm_name, classes=None, callbacks=()):
36
+ self._wt = _wasmtime()
37
+ wc = self._wt.component
38
+ self._wc = wc
39
+ self._engine = self._wt.Engine()
40
+ path = os.path.join(os.path.dirname(os.path.abspath(module_file)), wasm_name)
41
+ self._component = wc.Component.from_file(self._engine, path)
42
+ self._linker = wc.Linker(self._engine)
43
+ self._linker.add_wasip2()
44
+ # Callbacks: the component imports `callback-<i>` and calls it with the slot of the
45
+ # Python callable passed in for this call.
46
+ self._slots = {}
47
+ self._next_slot = 0
48
+ self._callback_error = None
49
+ for i, (params, result, zero) in enumerate(callbacks):
50
+ self._linker.root().add_func(f"callback-n{i}", self._host(params, result, zero))
51
+ self._classes = classes
52
+ # Re-entrant, so a callback running inside a call can't deadlock on it (it still can't
53
+ # call into this same component: a component isn't entered from its own import).
54
+ self._lock = threading.RLock()
55
+ self._generation = 0
56
+ self._fresh()
57
+
58
+ def _fresh(self):
59
+ self._store = self._wt.Store(self._engine)
60
+ self._store.set_wasi(self._wt.WasiConfig())
61
+ self._instance = self._linker.instantiate(self._store, self._component)
62
+ self._funcs = {}
63
+ # Objects made before a restart belong to the old instance.
64
+ self._generation += 1
65
+
66
+ def _func(self, name, in_classes=False):
67
+ key = (in_classes, name)
68
+ fn = self._funcs.get(key)
69
+ if fn is None:
70
+ scope = None
71
+ if in_classes:
72
+ scope = self._instance.get_export_index(self._store, self._classes)
73
+ index = self._instance.get_export_index(self._store, name, scope)
74
+ fn = self._funcs[key] = self._instance.get_func(self._store, index)
75
+ return fn
76
+
77
+ def _invoke(self, fn, wasm_args):
78
+ try:
79
+ raw = fn(self._store, *wasm_args)
80
+ except self._wt.WasmtimeError as e:
81
+ # A trap: a panic in the user's code. The instance can't be entered again.
82
+ self._fresh()
83
+ first = str(e).strip().splitlines()[0] if str(e).strip() else "a panic"
84
+ raise RustPanic(f"panicked inside the Wasm component: {first}") from None
85
+ fn.post_return(self._store)
86
+ return raw
87
+
88
+ def _host(self, params, result, zero):
89
+ def call_back(store, slot, *args):
90
+ try:
91
+ value = self._slots[slot](*[self._from(a, d) for a, d in zip(args, params)])
92
+ return None if result is None else self._to(value, result)
93
+ except BaseException as e: # noqa: BLE001 - raised again when the call returns
94
+ # The component can't unwind: it gets zero, and the exception is raised when
95
+ # the call into it returns, as in native builds.
96
+ if self._callback_error is None:
97
+ self._callback_error = e
98
+ return zero
99
+
100
+ return call_back
101
+
102
+ def call(self, name, params, result, args):
103
+ with self._lock:
104
+ used = []
105
+ wasm_args = [self._to(a, d, used) for a, d in zip(args, params)]
106
+ try:
107
+ raw = self._invoke(self._func(name), wasm_args)
108
+ finally:
109
+ for slot in used:
110
+ self._slots.pop(slot, None)
111
+ error, self._callback_error = self._callback_error, None
112
+ if error is not None:
113
+ raise error
114
+ return self._from(raw, result)
115
+
116
+ # Classes: resources of the component, held as (resource, generation).
117
+ def construct(self, res, params, args):
118
+ wasm_args = [self._to(a, d) for a, d in zip(args, params)]
119
+ with self._lock:
120
+ raw = self._invoke(self._func(f"[constructor]{res}", True), wasm_args)
121
+ return (raw, self._generation)
122
+
123
+ def _live(self, held):
124
+ if held is None:
125
+ raise ValueError("this object was closed")
126
+ if held[1] != self._generation:
127
+ raise RustPanic("this object was lost when the Wasm component restarted after a panic")
128
+ return held[0]
129
+
130
+ def method(self, held, res, name, params, result, args):
131
+ wasm_args = [self._to(a, d) for a, d in zip(args, params)]
132
+ with self._lock:
133
+ raw = self._invoke(self._func(f"[method]{res}.{name}", True), [self._live(held)] + wasm_args)
134
+ return self._from(raw, result)
135
+
136
+ def static(self, res, name, params, result, args):
137
+ wasm_args = [self._to(a, d) for a, d in zip(args, params)]
138
+ with self._lock:
139
+ raw = self._invoke(self._func(f"[static]{res}.{name}", True), wasm_args)
140
+ return self._from(raw, result)
141
+
142
+ def drop(self, held):
143
+ if held is None or held[1] != self._generation:
144
+ return
145
+ with self._lock:
146
+ held[0].drop(self._store)
147
+
148
+ # Python -> wasmtime
149
+ def _to(self, v, d, used=None):
150
+ kind = d[0]
151
+ if kind == "cb":
152
+ if not callable(v):
153
+ raise TypeError(f"expected a callable, not {type(v).__name__}")
154
+ slot = self._next_slot
155
+ self._next_slot = (self._next_slot + 1) % (1 << 32)
156
+ self._slots[slot] = v
157
+ if used is not None:
158
+ used.append(slot)
159
+ return slot
160
+ if kind == "bytes":
161
+ return v if isinstance(v, bytes) else bytes(v)
162
+ if kind == "list":
163
+ return [self._to(x, d[1]) for x in v]
164
+ if kind == "opt":
165
+ return None if v is None else self._to(v, d[1])
166
+ if kind == "rec":
167
+ r = self._wc.Record()
168
+ for py_name, wit_name, fd in d[1]._aw_fields:
169
+ setattr(r, wit_name, self._to(getattr(v, py_name), fd))
170
+ return r
171
+ if kind == "enum":
172
+ cls = d[1]
173
+ return cls._aw_cases[cls(v).name]
174
+ return v
175
+
176
+ # wasmtime -> Python
177
+ def _from(self, v, d):
178
+ if d is None:
179
+ return None
180
+ kind = d[0]
181
+ if kind == "list":
182
+ return [self._from(x, d[1]) for x in v]
183
+ if kind == "opt":
184
+ return None if v is None else self._from(v, d[1])
185
+ if kind == "rec":
186
+ cls = d[1]
187
+ return cls(**{py: self._from(getattr(v, wit), fd) for py, wit, fd in cls._aw_fields})
188
+ if kind == "enum":
189
+ cls = d[1]
190
+ by_case = {case: name for name, case in cls._aw_cases.items()}
191
+ return cls[by_case[v]]
192
+ if kind == "bytes":
193
+ return bytes(v)
194
+ if kind == "result":
195
+ ok = d[1]
196
+ # wasmtime tags a result only when ok and err could be confused by their Python
197
+ # types; otherwise a str is the error (its Err is always text).
198
+ if isinstance(v, self._wc.Variant):
199
+ if v.tag == "err":
200
+ raise NativeError(v.payload)
201
+ return self._from(v.payload, ok)
202
+ if isinstance(v, str) and (ok is None or ok[0] != "str"):
203
+ raise NativeError(v)
204
+ return self._from(v, ok)
205
+ return v
206
+
207
+
208
+ class GoModule:
209
+ """A Go file built as a WASI module (GOOS=wasip1, ``//go:wasmexport``).
210
+
211
+ Numbers and bools cross as themselves; a string goes in through memory the module allocates
212
+ (``antweft_alloc``/``antweft_free``) and comes back as a pointer and length packed in a u64.
213
+ A Go panic traps the module: it raises ``antweft.GoPanic`` and the module starts again fresh.
214
+ Calls are serialised, as for components.
215
+ """
216
+
217
+ def __init__(self, module_file, wasm_name):
218
+ self._wt = _wasmtime()
219
+ self._engine = self._wt.Engine()
220
+ path = os.path.join(os.path.dirname(os.path.abspath(module_file)), wasm_name)
221
+ self._module = self._wt.Module.from_file(self._engine, path)
222
+ self._lock = threading.Lock()
223
+ self._fresh()
224
+
225
+ def _fresh(self):
226
+ self._store = self._wt.Store(self._engine)
227
+ wasi = self._wt.WasiConfig()
228
+ wasi.inherit_stdout()
229
+ wasi.inherit_stderr()
230
+ self._store.set_wasi(wasi)
231
+ linker = self._wt.Linker(self._engine)
232
+ linker.define_wasi()
233
+ self._exports = linker.instantiate(self._store, self._module).exports(self._store)
234
+ self._exports["_initialize"](self._store)
235
+ self._memory = self._exports["memory"]
236
+
237
+ def call(self, name, kinds, result, args):
238
+ import operator
239
+
240
+ from . import GoPanic
241
+
242
+ with self._lock:
243
+ held = []
244
+ wasm_args = []
245
+ for value, kind in zip(args, kinds):
246
+ if kind == "str":
247
+ if not isinstance(value, str):
248
+ raise TypeError(f"{name}() expects str, not {type(value).__name__}")
249
+ data = value.encode()
250
+ p = self._exports["antweft_alloc"](self._store, len(data))
251
+ self._memory.write(self._store, data, p)
252
+ held.append(p)
253
+ wasm_args += [p, len(data)]
254
+ elif kind == "bool":
255
+ wasm_args.append(1 if value else 0)
256
+ elif kind == "float":
257
+ wasm_args.append(float(value))
258
+ else:
259
+ wasm_args.append(operator.index(value))
260
+ try:
261
+ raw = self._exports[name](self._store, *wasm_args)
262
+ except (self._wt.Trap, self._wt.WasmtimeError) as e:
263
+ self._fresh()
264
+ first = str(e).strip().splitlines()[0] if str(e).strip() else "a panic"
265
+ raise GoPanic(f"panicked inside the Wasm module: {first}") from None
266
+ for p in held:
267
+ self._exports["antweft_free"](self._store, p)
268
+ if result == "str":
269
+ ptr, size = raw >> 32, raw & 0xFFFFFFFF
270
+ return self._memory.read(self._store, ptr, ptr + size).decode() if size else ""
271
+ if result == "bool":
272
+ return raw != 0
273
+ return raw
Binary file