1 #!/usr/bin/env python32 """Echo plugin: the framed peer protocol with no SDK and no dependencies.3 4 The wire is `.f0rge/wiki/docs/protocol.md` sections 2 to 9. This file exists to5 show that a plugin needs the standard library, a socket, and an `open`; it uses6 no package from this repository. A short text part is echoed once, then the job7 is done.8 """9 10 import enum11 import json12 import socket13 import struct14 import sys15 import tomllib16 from pathlib import Path17 18 # The header is one 64-bit word, so its size and field layout are fixed.19 FRAME_HEADER_LEN = 820 21 # Python has no uint32 length field to inherit; the protocol ceiling is the22 # only bound on a payload.23 MAX_PAYLOAD = 0xFFFFFF24 25 # The highest wire version that this plugin speaks. It has no cache, so a26 # Wire 2 peer simply never sends cache frames.27 PROTOCOL_VERSION = 228 29 # A synchronous plugin runs one job at a time.30 MAX_INFLIGHT = 131 32 # Nothing is loaded, so the measured load time is zero.33 LOAD_MS = 034 35 # A recursive decoder needs a bound that is smaller than the interpreter stack.36 MAX_DEPTH = 6437 38 # The extension range that every peer reads and drops.39 EXTENSION_FIRST = 0x4040 EXTENSION_LAST = 0x7F41 42 # The channel and media type of a text echo.43 TEXT_CHANNEL = "text"44 TEXT_MIME = "text/plain; charset=utf-8"45 46 # The only capability that this plugin serves.47 CHAT = "chat"48 49 50 class FrameType(enum.IntEnum):51 """The sixteen assigned frame types of wire 1."""52 53 HELLO = 0x0154 WELCOME = 0x0255 CATALOGUE = 0x0356 GRANT = 0x0457 READY = 0x0558 WINDOW = 0x0659 PING = 0x0760 PONG = 0x0861 BYE = 0x0962 FATAL = 0x0A63 OPEN = 0x1064 ACCEPT = 0x1165 EVENT = 0x1266 DONE = 0x1367 REJECT = 0x1468 CANCEL = 0x1569 70 71 class CborError(Exception):72 """A CBOR item that the wire subset does not carry."""73 74 75 class FrameError(Exception):76 """A frame that wire 1 does not allow."""77 78 79 class ProtocolError(Exception):80 """A body or a session step that the grammar does not allow."""81 82 83 class CreditError(Exception):84 """An event that the caller's window cannot take."""85 86 87 def _head(major, arg):88 """The shortest head for one major type."""89 if arg < 24:90 return bytes([(major << 5) | arg])91 if arg <= 0xFF:92 return bytes([(major << 5) | 24, arg])93 if arg <= 0xFFFF:94 return bytes([(major << 5) | 25]) + arg.to_bytes(2, "big")95 if arg <= 0xFFFFFFFF:96 return bytes([(major << 5) | 26]) + arg.to_bytes(4, "big")97 if arg <= 0xFFFFFFFFFFFFFFFF:98 return bytes([(major << 5) | 27]) + arg.to_bytes(8, "big")99 raise CborError("integer does not fit 64 bits")100 101 102 def _encode(value, out, depth):103 if depth > MAX_DEPTH:104 raise CborError("nesting is deeper than the subset")105 if value is None:106 out.append(0xF6)107 elif value is False:108 out.append(0xF4)109 elif value is True:110 out.append(0xF5)111 elif isinstance(value, int):112 if value >= 0:113 out.extend(_head(0, value))114 else:115 out.extend(_head(1, -1 - value))116 elif isinstance(value, bytes):117 out.extend(_head(2, len(value)))118 out.extend(value)119 elif isinstance(value, str):120 body = value.encode("utf-8")121 out.extend(_head(3, len(body)))122 out.extend(body)123 elif isinstance(value, (list, tuple)):124 out.extend(_head(4, len(value)))125 for item in value:126 _encode(item, out, depth + 1)127 elif isinstance(value, dict):128 # RFC 8949 deterministic order: the bytewise order of encoded keys.129 entries = []130 for key, item in value.items():131 entries.append((encode(key), item))132 entries.sort(key=lambda entry: entry[0])133 out.extend(_head(5, len(entries)))134 for encoded_key, item in entries:135 out.extend(encoded_key)136 _encode(item, out, depth + 1)137 else:138 raise CborError("value is not in the cbor subset")139 140 141 def encode(value):142 """The canonical bytes of one CBOR item."""143 out = bytearray()144 _encode(value, out, 0)145 return bytes(out)146 147 148 def _argument(data, pos, ai):149 if ai < 24:150 return ai, pos151 widths = {24: 1, 25: 2, 26: 4, 27: 8}152 width = widths.get(ai)153 if width is None:154 raise CborError("indefinite or reserved length")155 end = pos + width156 if end > len(data):157 raise CborError("the item ends before its data")158 arg = int.from_bytes(data[pos:end], "big")159 shortest = {24: 24, 25: 0x100, 26: 0x10000, 27: 0x100000000}[ai]160 if ai == 24:161 shortest = 24162 if arg < shortest:163 raise CborError("a length is not in its shortest form")164 return arg, end165 166 167 def _decode(data, pos, depth):168 if depth > MAX_DEPTH:169 raise CborError("nesting is deeper than the subset")170 if pos >= len(data):171 raise CborError("the item ends before its data")172 initial = data[pos]173 major = initial >> 5174 ai = initial & 0x1F175 pos += 1176 if major == 7:177 if ai == 20:178 return False, pos179 if ai == 21:180 return True, pos181 if ai == 22:182 return None, pos183 raise CborError("simple value is not in the subset")184 arg, pos = _argument(data, pos, ai)185 if major == 0:186 return arg, pos187 if major == 1:188 return -1 - arg, pos189 if major in (2, 3):190 end = pos + arg191 if end > len(data):192 raise CborError("the item ends before its data")193 body = data[pos:end]194 if major == 2:195 return bytes(body), end196 try:197 return body.decode("utf-8"), end198 except UnicodeDecodeError as error:199 raise CborError("a text string is not UTF-8") from error200 if major == 4:201 items = []202 for _ in range(arg):203 item, pos = _decode(data, pos, depth + 1)204 items.append(item)205 return items, pos206 if major == 5:207 result = {}208 for _ in range(arg):209 key, pos = _decode(data, pos, depth + 1)210 if not isinstance(key, (str, int, bytes, bool)) and key is not None:211 raise CborError("a map key is not a scalar")212 if key in result:213 raise CborError("the same key appears twice in one map")214 item, pos = _decode(data, pos, depth + 1)215 result[key] = item216 return result, pos217 raise CborError(f"major type {major} is not in the subset")218 219 220 def decode(data):221 """The one CBOR item in `data`; trailing bytes are an error."""222 value, pos = _decode(data, 0, 0)223 if pos != len(data):224 raise CborError("bytes follow the item")225 return value226 227 228 def is_extension(kind):229 """True for a type that a peer reads and drops."""230 return EXTENSION_FIRST <= kind <= EXTENSION_LAST231 232 233 def _recv_exact(sock, size):234 out = bytearray()235 while len(out) < size:236 chunk = sock.recv(size - len(out))237 if not chunk:238 return None239 out.extend(chunk)240 return bytes(out)241 242 243 def read_frame(sock):244 """One frame as `(stream, kind, payload)`, or None at a clean close."""245 header = _recv_exact(sock, FRAME_HEADER_LEN)246 if header is None:247 return None248 length, stream, kind, flags = struct.unpack("<IHBB", header)249 if length > MAX_PAYLOAD:250 raise FrameError("the payload is larger than the wire ceiling")251 if flags != 0:252 raise FrameError("the flags byte is not zero")253 if not is_extension(kind):254 try:255 FrameType(kind)256 except ValueError as error:257 raise FrameError(f"type {kind:#04x} is not assigned") from error258 payload = _recv_exact(sock, length)259 if payload is None:260 raise FrameError("the frame ends before its payload")261 return stream, kind, payload262 263 264 def write_frame(sock, stream, kind, body):265 """Writes one frame with a CBOR body."""266 payload = encode(body)267 if len(payload) > MAX_PAYLOAD:268 raise FrameError("the payload is larger than the wire ceiling")269 header = struct.pack("<IHBB", len(payload), stream, int(kind), 0)270 sock.sendall(header + payload)271 272 273 def load_catalogue(root):274 """The catalogue from `target.toml` and `models/*.toml`."""275 with (root / "target.toml").open("rb") as handle:276 target_doc = tomllib.load(handle)277 target = target_doc["target"]278 models = []279 for path in sorted((root / "models").glob("*.toml")):280 with path.open("rb") as handle:281 document = tomllib.load(handle)282 model = document["model"]283 capabilities = {}284 for name, spec in document.get("capabilities", {}).items():285 capabilities[name] = {286 "vocab": spec.get("vocab", ""),287 "parts": list(spec.get("parts", [])),288 "channels": list(spec.get("channels", [])),289 "limits": {290 key: int(value) for key, value in spec.get("limits", {}).items()291 },292 "cancel": spec.get("cancel", "token"),293 "stops": spec.get("stops", "plugin"),294 "queue": spec.get("queue", "none"),295 }296 models.append(297 {298 "serve": model["serve"],299 "alias_of": model.get("alias_of"),300 "weights_bytes": int(model.get("weights_bytes", 0)),301 "load_ms": int(model.get("load_ms", 0)),302 "capabilities": capabilities,303 }304 )305 return {306 "target": {307 "id": target["name"],308 "backend": target["backend"],309 "arch": list(target.get("arch", [])),310 "devices": int(target.get("devices", 0)),311 "vram_mb": [int(mb) for mb in target.get("vram_mb", [])],312 },313 "models": models,314 }315 316 317 def _version_accepts(range_value):318 """True when a hello version, integer or [min, max], includes this peer."""319 if isinstance(range_value, int):320 return 1 <= range_value <= PROTOCOL_VERSION321 if isinstance(range_value, list) and len(range_value) == 2:322 return range_value[0] <= PROTOCOL_VERSION and range_value[1] >= 1323 return False324 325 326 def _text_of(parts):327 """The inline text bytes of every text part, in wire order."""328 chunks = []329 for part in parts:330 if part.get("kind") == "text" and "inline" in part:331 chunk = part["inline"]332 if not isinstance(chunk, bytes):333 raise ProtocolError("an inline part is not a byte string")334 chunks.append(chunk)335 return b"".join(chunks)336 337 338 def _served(catalogue):339 return {model["serve"]: model for model in catalogue["models"]}340 341 342 def run_job(sock, stream, body, catalogue):343 """Answers one `open`: accept, one text event, done."""344 if stream == 0:345 raise ProtocolError("a job needs a nonzero stream")346 model = body.get("model")347 capability = body.get("capability")348 served = _served(catalogue)349 if model not in served:350 write_frame(351 sock,352 stream,353 FrameType.REJECT,354 {"code": "unknown_model", "detail": model},355 )356 return357 if capability not in served[model]["capabilities"]:358 write_frame(359 sock,360 stream,361 FrameType.REJECT,362 {"code": "capability", "detail": capability},363 )364 return365 text = _text_of(body.get("parts", []))366 credit = body.get("credit", 0)367 if not isinstance(credit, int) or credit < 0:368 raise ProtocolError("credit is not a uint")369 if credit == 0:370 # The worker cannot write one byte, so the only honest terminal is a371 # cancellation. The gate uses this to prove that an active job stops.372 write_frame(sock, stream, FrameType.ACCEPT, {"est_ms": None})373 write_frame(374 sock,375 stream,376 FrameType.DONE,377 {"outcome": "cancelled", "artifacts": [], "usage": {}, "meta": None},378 )379 return380 if len(text) > credit:381 raise CreditError(f"{len(text)} bytes of text with {credit} bytes of credit")382 write_frame(sock, stream, FrameType.ACCEPT, {"est_ms": None})383 write_frame(384 sock,385 stream,386 FrameType.EVENT,387 {"ch": TEXT_CHANNEL, "mime": TEXT_MIME, "data": text},388 )389 write_frame(390 sock,391 stream,392 FrameType.DONE,393 {"outcome": "completed", "artifacts": [], "usage": {}, "meta": None},394 )395 396 397 def serve(sock, catalogue):398 """The server side of protocol.md section 6 until the peer closes."""399 first = read_frame(sock)400 if first is None:401 return402 stream, kind, payload = first403 if stream != 0 or kind != FrameType.HELLO:404 raise ProtocolError("the session starts with hello on stream 0")405 hello = decode(payload)406 if not _version_accepts(hello.get("v")):407 write_frame(408 sock,409 0,410 FrameType.FATAL,411 {"code": "version", "detail": str(hello.get("v"))},412 )413 return414 write_frame(415 sock,416 0,417 FrameType.WELCOME,418 {"v": PROTOCOL_VERSION, "max_inflight": MAX_INFLIGHT},419 )420 write_frame(sock, 0, FrameType.CATALOGUE, catalogue)421 422 while True:423 frame = read_frame(sock)424 if frame is None:425 return426 stream, kind, payload = frame427 if is_extension(kind):428 continue429 body = decode(payload)430 if kind == FrameType.GRANT:431 if stream != 0:432 raise ProtocolError("grant is a session frame")433 write_frame(sock, 0, FrameType.READY, {"load_ms": LOAD_MS})434 elif kind == FrameType.OPEN:435 try:436 run_job(sock, stream, body, catalogue)437 except CreditError as why:438 # Refusing is the honest answer to a window that the job would439 # overrun; the session stays open for the next job.440 write_frame(441 sock,442 stream,443 FrameType.REJECT,444 {"code": "credit", "detail": str(why)},445 )446 elif kind == FrameType.PING:447 write_frame(sock, 0, FrameType.PONG, {"t": body.get("t", 0)})448 elif kind in (FrameType.WINDOW, FrameType.PONG):449 # A synchronous job has already finished, so there is no window to450 # raise and no tick to echo.451 continue452 elif kind == FrameType.CANCEL:453 # Every job ends in the same call that reads it. A cancel that454 # arrives here names a stream that is already closed.455 continue456 elif kind == FrameType.BYE:457 return458 elif kind == FrameType.FATAL:459 return460 else:461 raise ProtocolError(f"{kind:#04x} does not belong on this session")462 463 464 def main(argv):465 root = Path(__file__).resolve().parent466 if len(argv) == 2 and argv[1] == "--describe":467 catalogue = load_catalogue(root)468 print(json.dumps(catalogue, sort_keys=True, separators=(",", ":")))469 return 0470 if len(argv) != 3 or argv[1] != "--socket":471 raise SystemExit("usage: plugin.py --describe | --socket <path>")472 path = argv[2]473 catalogue = load_catalogue(root)474 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:475 sock.connect(path)476 serve(sock, catalogue)477 return 0478 479 480 if __name__ == "__main__":481 sys.exit(main(sys.argv))