aboutsummaryrefslogtreecommitdiffstats
path: root/bsfs/front/builder.py
blob: b1d488b0a02d374edf70f3926ef2ecba1b15d965 (plain)
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

# imports
import typing

# bsfs imports
from bsfs.graph import Graph, ac
from bsfs.triple_store import TripleStoreBase, SparqlStore
from bsfs.utils import URI, errors

# exports
__all__: typing.Sequence[str] = (
    'build_graph',
    )

# constants
_graph_classes = {
    'Graph': Graph,
    }

_backend_classes = {
    'SparqlStore': SparqlStore,
    }


## code ##

def build_backend(cfg: typing.Any) -> TripleStoreBase:
    """Build and return a backend from user-provided config."""
    # essential checks
    if not isinstance(cfg, dict):
        raise TypeError(cfg)
    if len(cfg) != 1:
        raise errors.ConfigError(f'expected a single key that identifies the backend class, found {list(cfg)}')
    # unpack from config
    name = next(iter(cfg))
    args = cfg[name]
    # check name
    if name not in _backend_classes:
        raise errors.ConfigError(f'{name} is not a valid triple store class name')
    # build and return backend
    cls = _backend_classes[name]
    return cls.Open(**args)


def build_graph(cfg: typing.Any) -> Graph:
    """Build and return a Graph from user-provided config."""
    # essential checks
    if not isinstance(cfg, dict):
        raise TypeError(cfg)
    if len(cfg) != 1:
        raise errors.ConfigError(f'expected a single key that identifies the graph class, found {list(cfg)}')
    # unpack from config
    name = next(iter(cfg))
    args = cfg[name]
    # check name
    if name not in _graph_classes:
        raise errors.ConfigError(f'{name} is not a valid graph class name')
    # check user argument
    if 'user' not in args:
        raise errors.ConfigError('required argument "user" is not provided')
    user = URI(args['user'])
    # check backend argument
    if 'backend' not in args:
        raise errors.ConfigError('required argument "backend" is not provided')
    backend = build_backend(args['backend'])
    # build access controls
    access_controls = ac.NullAC(backend, user)
    # build and return graph
    cls = _graph_classes[name]
    return cls(backend, access_controls)

## EOF ##