Source code for fleetmesh_core.wire.schema_files

#!/usr/bin/env python3
"""The one place the reference library reads its published schema files.

Every module used to `json.load(open(...))` schema/constants.json for itself:
sixteen file descriptors left to the garbage collector, three of them without
an encoding, and no single place to say where the schema lives. Each loader
here opens the file once, under `with`, as UTF-8, and lru_cache hands the same
parsed object to every importer - so window.C, capacity.C and peering.CONSTANTS
are views of one document, exactly as the digest promises.

Where the files are: the `fleetmesh_schema` package carries them (installed
or as the sibling checkout on sys.path); a bare checkout of this repo with the
`schema -> ../schema/schema` symlink and no such package falls back to that.
Either way ROOT is the directory holding `schema/` and `schemas/`, which is
what the few callers that build their own paths need.

Standard library only. Nothing here reads the network or the wall clock.
"""
from __future__ import annotations

import functools
import json
import os
from typing import Any

try:
    import fleetmesh_schema as _pkg
    ROOT = _pkg.HERE
except ImportError:                       # in-tree layout without the package
    _pkg = None
    cur = os.path.dirname(os.path.abspath(__file__))
    candidate = cur
    while candidate and candidate != os.path.dirname(candidate):
        if os.path.isdir(os.path.join(candidate, 'schema')) or os.path.isdir(os.path.join(candidate, 'schemas')):
            break
        candidate = os.path.dirname(candidate)
    ROOT = candidate or os.path.abspath(os.path.join(cur, '..', '..'))
SCHEMA_DIR = os.path.join(ROOT, 'schema')
SCHEMAS_DIR = os.path.join(ROOT, 'schemas')


[docs]def path(name: str) -> str: """Absolute path of a file under schema/ (constants.json, kinds.json, ...).""" return os.path.join(SCHEMA_DIR, name)
[docs]def schema_path(*parts: str) -> str: """Absolute path of a JSON Schema document under schemas/ (plane, ..., file).""" return os.path.join(SCHEMAS_DIR, *parts)
[docs]@functools.lru_cache(maxsize=None) def load_json(name: str) -> Any: """Parse one schema file, once. The path is in any error so a broken checkout names itself instead of surfacing as a KeyError three modules later.""" p = path(name) try: with open(p, encoding='utf-8') as fh: return json.load(fh) except (OSError, json.JSONDecodeError) as e: raise RuntimeError('cannot read schema file %s: %s' % (p, e)) from e
from .interfaces import ( SchemaConstantsDocument, SchemaKindsDocument, SchemaMessagesDocument, )
[docs]def load_constants() -> SchemaConstantsDocument: return load_json('constants.json')
[docs]def load_kinds() -> SchemaKindsDocument: """The whole kinds.json document (callers index ['kinds'] or ['version']).""" return load_json('kinds.json')
[docs]def load_messages() -> SchemaMessagesDocument: return load_json('messages.json')
[docs]@functools.lru_cache(maxsize=None) def digest() -> str: """The published protocol digest, schema/DIGEST, stripped.""" p = path('DIGEST') try: with open(p, encoding='utf-8') as fh: return fh.read().strip() except OSError as e: raise RuntimeError('cannot read schema file %s: %s' % (p, e)) from e