Repository navigation
Expand file tree
/
Copy pathengine.py
More file actions
339 lines (287 loc) · 13.3 KB
/
Copy pathengine.py
File metadata and controls
339 lines (287 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
"""MEOS execution engines.
The runtime server is contract-driven: it builds routes/validation from the
enriched catalog and, per call, performs the universal pipeline the `wire`
model implies — *decode each serialized argument, invoke the function, encode
the result*. The actual MEOS calls happen behind the ``Engine`` seam.
Two engines ship:
- ``CtypesEngine`` — the real one: ``dlopen`` a built ``libmeos`` and call
``x-meos.decode`` / the function / ``x-meos.encode`` by symbol. Requires a
compiled MEOS shared library (set ``MEOS_LIBRARY_PATH``); the marshalling
is unit-tested against a fake library but, by design, the literal native
linkage is environment-gated.
- ``StubEngine`` — no MEOS runtime: lets the server, routing, request
validation and error mapping run and be exercised without a build. It
returns deterministic placeholders and is **not** a computation engine.
Engine contract (all tags are simple strings the app layer assigns from the
``wire`` model: ``ptr`` for a decoded opaque value, ``str``/``int``/
``double``/``bool``/``enum`` for scalars, ``void`` for no result):
decode(fn_name, value:str) -> handle (opaque)
invoke(fn_name, args:[(tag,val)], rt) -> handle|scalar|None
encode(fn_name, handle, aux, outparams) -> str
"""
from __future__ import annotations
class MeosError(Exception):
"""A MEOS-level failure; mapped by the server to HTTP 400."""
def __init__(self, message: str, code: int = 1):
super().__init__(message)
self.code = code
class Engine:
# ``aux`` is a list of ``(tag, value)`` for the trailing formatting args
# of the in/out wrapper (e.g. ``[("int", 15)]`` for ``temporal_out``'s
# ``maxdd``), supplied from the catalog's ``decode_aux``/``encode_aux``.
def decode(self, fn_name: str, value: str, aux=()):
raise NotImplementedError
def invoke(self, fn_name: str, args: list, result_tag: str):
raise NotImplementedError
def encode(self, fn_name: str, handle, aux=(), outparams=()) -> str:
"""``outparams``: the ``(position, cType)`` of the writer's out-parameters,
from the catalog's ``shape.outParams`` (#writer_outparams of server/app.py)."""
raise NotImplementedError
def invoke_outparam(self, fn_name: str, args: list, out_ctype: str,
presence: bool):
"""``bool f(.., T *result)`` — return ``(present, value)``."""
raise NotImplementedError
def invoke_array(self, fn_name: str, args: list):
"""``Elem **f(.., int *count)`` — return a list of element handles."""
raise NotImplementedError
def invoke_string(self, fn_name: str, args: list):
"""``char *f(.., size_t *size_out)`` — return the string, read for the
size the function writes, as #invoke_array reads its trailing count."""
raise NotImplementedError
def invoke_counted_array(self, fn_name: str, args: list, count: int):
"""``Elem **f(Elem **arr, int count, ..)`` — return the ``count`` element
handles of an array as long as an array argument."""
raise NotImplementedError
def close(self) -> None:
pass
class StubEngine(Engine):
"""Non-computing placeholder so the server runs without a MEOS build."""
name = "stub"
def decode(self, fn_name, value, aux=()):
return {"_stub_handle": fn_name, "value": value}
def invoke(self, fn_name, args, result_tag):
if result_tag == "void":
return None
if result_tag == "ptr":
return {"_stub_handle": fn_name}
return {"str": "", "int": 0, "double": 0.0,
"bool": False, "enum": ""}.get(result_tag, "")
def encode(self, fn_name, handle, aux=(), outparams=()):
return f"<stub:{fn_name}>"
def invoke_string(self, fn_name, args):
# the placeholder string #invoke answers for a "str" result
return ""
def invoke_outparam(self, fn_name, args, out_ctype, presence):
return True, 0
def invoke_array(self, fn_name, args):
return []
def invoke_counted_array(self, fn_name, args, count):
return []
class CtypesEngine(Engine):
"""Calls a built libmeos via ctypes, driven entirely by the wire model.
Every opaque value is an anonymous ``void *`` — no struct layout is ever
needed, because the catalog already reduced every exposable function to
*scalars + decode/encode of opaque pointers*.
"""
name = "ctypes"
def __init__(self, library_path: str):
import ctypes
self._ct = ctypes
self.lib = ctypes.CDLL(library_path)
self._argmap = {
"ptr": ctypes.c_void_p, "str": ctypes.c_char_p,
"int": ctypes.c_long, "double": ctypes.c_double,
"bool": ctypes.c_int, "enum": ctypes.c_int,
}
self._retmap = {
"ptr": ctypes.c_void_p, "str": ctypes.c_char_p,
"int": ctypes.c_long, "double": ctypes.c_double,
"bool": ctypes.c_int,
}
self._last_error = None
if hasattr(self.lib, "meos_initialize"):
self.lib.meos_initialize.restype = None
try:
self.lib.meos_initialize()
except TypeError:
self.lib.meos_initialize(None)
# MEOS's default error handler calls exit() — a single bad input
# would kill the whole server. Replace it with one that records the
# error so the request can be turned into a 400 instead.
if hasattr(self.lib, "meos_initialize_error_handler"):
handler_t = ctypes.CFUNCTYPE(
None, ctypes.c_int, ctypes.c_int, ctypes.c_char_p)
def _on_error(level, code, msg):
self._last_error = (
int(code),
msg.decode(errors="replace") if msg else "MEOS error")
self._err_cb = handler_t(_on_error) # keep a ref alive
self.lib.meos_initialize_error_handler.argtypes = [handler_t]
self.lib.meos_initialize_error_handler.restype = None
self.lib.meos_initialize_error_handler(self._err_cb)
def _sym(self, name: str):
try:
return getattr(self.lib, name)
except AttributeError as e:
raise MeosError(f"unknown MEOS symbol: {name}", 404) from e
def _raise_if_error(self) -> None:
if self._last_error is not None:
code, msg = self._last_error
self._last_error = None
raise MeosError(msg, code)
def _aux_ctypes(self, aux):
types = [self._argmap[t] for t, _ in aux]
vals = [v.encode() if t == "str" and isinstance(v, str) else v
for t, v in aux]
return types, vals
def decode(self, fn_name, value, aux=()):
self._last_error = None
f = self._sym(fn_name)
atypes, avals = self._aux_ctypes(aux)
f.argtypes = [self._ct.c_char_p, *atypes]
f.restype = self._ct.c_void_p
h = f(value.encode(), *avals)
self._raise_if_error()
if not h:
raise MeosError(f"{fn_name} failed to parse input")
return h
def invoke(self, fn_name, args, result_tag):
self._last_error = None
f = self._sym(fn_name)
ct = self._ct
argtypes, cargs = [], []
for tag, val in args:
if tag == "ptrarray": # Elem **arr from a JSON list
arr = (ct.c_void_p * len(val))(*[ct.c_void_p(h)
for h in val])
argtypes.append(ct.POINTER(ct.c_void_p))
cargs.append(arr)
else:
argtypes.append(self._argmap[tag])
cargs.append(val.encode() if tag == "str"
and isinstance(val, str) else val)
f.argtypes = argtypes
f.restype = self._retmap.get(result_tag) # None == void
r = f(*cargs)
self._raise_if_error()
return r
def encode(self, fn_name, handle, aux=(), outparams=()):
"""``char *f(const T *, aux..., size_t *size_out)``: the writer called with its
own signature. ``outparams`` are the ``(position, cType)`` of the parameters
the catalog states in its ``shape.outParams``, positions counted from the value
at 0; each gets a slot of its own, as #invoke_outparam gives its result one,
and the trailing inputs fill the other positions in order. A writer handing
back its size in a ``size_t *`` is read for that many bytes."""
self._last_error = None
f = self._sym(fn_name)
ct = self._ct
atypes, avals = self._aux_ctypes(aux)
outs = dict(outparams)
argtypes, cargs, slots = [ct.c_void_p], [handle], {}
rest = iter(zip(atypes, avals))
for pos in range(1, 1 + len(atypes) + len(outs)):
if pos in outs:
slot = self._pointee_ctype(outs[pos])()
slots[pos] = (outs[pos], slot)
argtypes.append(ct.POINTER(type(slot)))
cargs.append(ct.byref(slot))
else:
t, v = next(rest)
argtypes.append(t)
cargs.append(v)
f.argtypes = argtypes
if not slots:
f.restype = ct.c_char_p
r = f(*cargs)
self._raise_if_error()
return r.decode() if r else None
f.restype = ct.c_void_p
r = f(*cargs)
self._raise_if_error()
if not r:
return None
sizes = [s.value for c, s in slots.values()
if " ".join(c.replace("*", " ").split()) == "size_t"]
raw = ct.string_at(r, sizes[0]) if sizes else ct.string_at(r)
# The size of a string MEOS writes counts its terminating NUL
# (``datum_as_wkb`` sizes a hex buffer ``2 * size + 1``).
return (raw[:-1] if raw.endswith(b"\0") else raw).decode()
def _pointee_ctype(self, out_ctype: str):
ct = self._ct
base = " ".join(
out_ctype.replace("const", "").replace("*", " ").split())
return {
"double": ct.c_double, "float": ct.c_float,
"long long": ct.c_longlong, "unsigned long": ct.c_ulong,
"long": ct.c_long, "unsigned int": ct.c_uint,
"short": ct.c_short, "unsigned char": ct.c_ubyte,
"signed char": ct.c_byte, "size_t": ct.c_size_t,
}.get(base, ct.c_int)
def invoke_outparam(self, fn_name, args, out_ctype, presence):
self._last_error = None
f = self._sym(fn_name)
ct = self._ct
# T **result -> the slot holds an opaque pointer (c_void_p);
# T *result -> a scalar slot.
slot = (ct.c_void_p() if out_ctype.count("*") >= 2
else self._pointee_ctype(out_ctype)())
f.argtypes = [self._argmap[t] for t, _ in args] + [ct.POINTER(
type(slot))]
f.restype = ct.c_int if presence else None
cargs = [v.encode() if t == "str" and isinstance(v, str) else v
for t, v in args]
ret = f(*cargs, ct.byref(slot))
self._raise_if_error()
present = bool(ret) if presence else True
return present, slot.value
def invoke_array(self, fn_name, args):
# Elem **f(leading..., int *count): MEOS allocates the array and
# writes the length through the trailing byref count.
self._last_error = None
f = self._sym(fn_name)
ct = self._ct
n = ct.c_int()
f.argtypes = [self._argmap[t] for t, _ in args] + [
ct.POINTER(ct.c_int)]
f.restype = ct.c_void_p
cargs = [v.encode() if t == "str" and isinstance(v, str) else v
for t, v in args]
ret = f(*cargs, ct.byref(n))
self._raise_if_error()
count = n.value
if not ret or count <= 0:
return []
arr = ct.cast(ret, ct.POINTER(ct.c_void_p))
return [arr[i] for i in range(count)]
def invoke_string(self, fn_name, args):
# char *f(leading..., size_t *size_out): MEOS writes the size of the
# string, its terminating NUL included, through the trailing byref
# size, as #invoke_array reads its count; the string is read for
# that many bytes rather than scanned for its terminator.
self._last_error = None
f = self._sym(fn_name)
ct = self._ct
n = ct.c_size_t()
f.argtypes = [self._argmap[t] for t, _ in args] + [
ct.POINTER(ct.c_size_t)]
f.restype = ct.c_void_p
cargs = [v.encode() if t == "str" and isinstance(v, str) else v
for t, v in args]
ret = f(*cargs, ct.byref(n))
self._raise_if_error()
if not ret:
return None
return ct.string_at(ret, n.value - 1).decode()
def invoke_counted_array(self, fn_name, args, count):
# Elem **f(Elem **arr, int count, ...): MEOS allocates an array as long
# as the argument array, so its length is the one the caller passed.
ret = self.invoke(fn_name, args, "ptr")
if not ret or count <= 0:
return []
arr = self._ct.cast(ret, self._ct.POINTER(self._ct.c_void_p))
return [arr[i] for i in range(count)]
def from_env() -> Engine:
"""``CtypesEngine`` if ``MEOS_LIBRARY_PATH`` is set, else ``StubEngine``."""
import os
path = os.environ.get("MEOS_LIBRARY_PATH")
return CtypesEngine(path) if path else StubEngine()