Source code for fleetmesh_core.conformance.conformance

"""The conformance protocol: how a harness drives any implementation.

A harness and an implementation under test speak JSON lines over a pipe. One
request per line in, one reply per line out, matched by `id`:

    -> {"id": 1, "op": "fingerprint.of", "args": {"ids": ["00..01", "00..02"]}}
    <- {"id": 1, "result": "9f3c..."}

    -> {"id": 2, "op": "no.such.op", "args": {}}
    <- {"id": 2, "error": {"code": "unsupported", "message": "no.such.op"}}

The first request is always `hello` with no args; the reply names the
implementation and lists the ops it answers. Ops the implementation does not
list are SKIPPED by the harness, never failed - a partial implementation gets an
honest score for the planes it speaks. Three error codes exist:

    unsupported  the op is not in this implementation's catalogue
    bad_args     the args did not have the shape the catalogue says
    internal     the implementation fell over; always a bug in it

An op whose *protocol* answer can be a refusal (a malformed event, a rejected
URL) returns that refusal as its RESULT in the shape the catalogue states -
usually `{"refused": "<why>"}` - so a harness can pin the reason. Protocol
errors are reserved for the harness-implementation contract itself.

Bytes are hex strings; there are no other encodings. Every value is plain JSON
so an implementation in any language can take part. The catalogue of ops, their
plane and their argument shapes lives in `conformance_ops.py`; this module is the
wire and the loop. Run the reference implementation as

    python3 -m fleetmesh_core.conformance            # from a checkout with the ref symlink
    python3 -m fleetmesh_core.conformance # from the core package
"""
from __future__ import annotations

import json
import sys
from typing import Any, Callable, Mapping, Optional, TextIO, TypedDict

IMPLEMENTATION = 'fleetmesh-core (python reference)'

Args = Mapping[str, Any]
Handler = Callable[[Args], Any]


[docs]class Op(TypedDict): plane: str about: str handler: Handler
[docs]class ArgError(ValueError): """Raised by a handler when `args` is not what the catalogue promised."""
[docs]class Refused(Exception): """A protocol-level refusal a handler wants returned as `{'refused': why}`."""
[docs]def reply(id_: Any, result: Any) -> Mapping[str, Any]: return {'id': id_, 'result': result}
[docs]def error(id_: Any, code: str, message: str) -> Mapping[str, Any]: return {'id': id_, 'error': {'code': code, 'message': message}}
[docs]def answer(ops: Mapping[str, Op], request: Mapping[str, Any]) -> Mapping[str, Any]: """Answer one request against a catalogue. Never raises.""" id_ = request.get('id') op = request.get('op') if op == 'hello': return reply(id_, {'implementation': IMPLEMENTATION, 'ops': sorted(ops)}) if not isinstance(op, str) or op not in ops: return error(id_, 'unsupported', str(op)) args = request.get('args', {}) if not isinstance(args, dict): return error(id_, 'bad_args', 'args must be an object') try: return reply(id_, ops[op]['handler'](args)) except Refused as e: return reply(id_, {'refused': str(e)}) except (ArgError, KeyError, TypeError, ValueError) as e: return error(id_, 'bad_args', '%s: %s' % (type(e).__name__, e)) except Exception as e: # noqa: BLE001 - the loop must survive any handler return error(id_, 'internal', '%s: %s' % (type(e).__name__, e))
[docs]def serve(ops: Mapping[str, Op], inp: Optional[TextIO] = None, out: Optional[TextIO] = None) -> int: """Read requests until EOF. Returns the number answered.""" src: TextIO = inp if inp is not None else sys.stdin dst: TextIO = out if out is not None else sys.stdout n = 0 for line in src: line = line.strip() if not line: continue try: request = json.loads(line) except ValueError as e: dst.write(json.dumps(error(None, 'bad_args', 'not JSON: %s' % e)) + '\n') dst.flush() continue if not isinstance(request, dict): request = {'id': None, 'op': None} dst.write(json.dumps(answer(ops, request), sort_keys=True) + '\n') dst.flush() n += 1 return n
[docs]def main() -> int: # Running as __main__ makes this file a second module, with a second `Refused` # class that the ops module would not raise. Serve from the imported copy. pkg = __package__ or 'fleetmesh_core.conformance' import importlib conf = importlib.import_module(pkg + '.conformance') ops = importlib.import_module(pkg + '.conformance_ops') conf.serve(ops.OPS) return 0
if __name__ == '__main__': sys.exit(main())