aboutsummaryrefslogtreecommitdiff
path: root/src/hydrilla/server/serve.py
blob: 8f0d557ba528700899a9f06b9b597d99186cdd9a (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
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
# SPDX-License-Identifier: AGPL-3.0-or-later

# Main repository logic.
#
# This file is part of Hydrilla
#
# Copyright (C) 2021, 2022 Wojtek Kosior
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
#
# I, Wojtek Kosior, thereby promise not to sue for violation of this
# file's license. Although I request that you do not make use this code
# in a proprietary program, I am not going to enforce this in court.

# Enable using with Python 3.7.
from __future__ import annotations

import re
import os
import pathlib
import json
import logging

from pathlib import Path
from hashlib import sha256
from abc import ABC, abstractmethod
from typing import Optional, Union, Iterable, TypeVar, Generic

import click
import flask

from werkzeug import Response

from .. import _version, versions, json_instances
from ..item_infos import ResourceInfo, MappingInfo, VersionedItemInfo
from ..translations import smart_gettext as _, translation as make_translation
#from ..url_patterns import PatternTree
from . import config

here = Path(__file__).resolve().parent

generated_by = {
    'name': 'hydrilla.server',
    'version': _version.version
}

    # def as_query_result(self) -> dict[str, Union[str, list[int]]]:
    #     """
    #     Produce a json.dump()-able object describing this mapping as one of a
    #     collection of query results.
    #     """
    #     return {
    #         'version':    self.version,
    #         'identifier': self.identifier,
    #         'long_name':  self.long_name
    #     }

class Malcontent:
    """
    Represent a directory with files that can be loaded and served by Hydrilla.
    """
    def __init__(self, malcontent_dir_path: Path):
        """
        When an instance of Malcontent is constructed, it searches
        malcontent_dir_path for serveable site-modifying packages and loads
        them into its data structures.
        """
        self.resource_infos: dict[str, VersionedItemInfo[ResourceInfo]] = {}
        self.mapping_infos:  dict[str, VersionedItemInfo[MappingInfo]]  = {}

        self.pattern_tree: PatternTree[MappingInfo] = PatternTree()

        self.malcontent_dir_path = malcontent_dir_path

        if not self.malcontent_dir_path.is_dir():
            raise ValueError(_('malcontent_dir_path_not_dir_{}')
                             .format(malcontent_dir_path))

        for item_type in ('mapping', 'resource'):
            type_path = self.malcontent_dir_path / item_type
            if not type_path.is_dir():
                continue

            for subpath in type_path.iterdir():
                if not subpath.is_dir():
                    continue

                for ver_file in subpath.iterdir():
                    try:
                        self._load_item(item_type, ver_file)
                    except Exception as e:
                        if flask.current_app._hydrilla_werror:
                            raise e from None

                        msg = _('couldnt_load_item_from_{}').format(ver_file)
                        logging.error(msg, exc_info=True)

        self._report_missing()
        self._finalize()

    @staticmethod
    def _register_info(infos: dict[str, VersionedItemInfo[VersionedType]],
                       identifier: str, item_info: VersionedType) -> None:
        """
        ...........
        """
        infos.setdefault(identifier, VersionedItemInfo())\
             .register(item_info)

    def _load_item(self, item_type: str, ver_file: Path) -> None:
        """
        Reads, validates and autocompletes serveable mapping/resource
        definition, then registers information from it in data structures.
        """
        version    = versions.parse_version(ver_file.name)
        identifier = ver_file.parent.name

        item_json, major = util.load_instance_from_file(ver_file)

        util.validator_for(f'api_{item_type}_description-{major}.schema.json')\
            .validate(item_json)

        # Assertion needed for mypy. If validation passed, this should not fail.
        assert major is not None

        item_info: ItemInfo = ResourceInfo(item_json, major) \
            if item_type == 'resource' else MappingInfo(item_json, major)

        if item_info.identifier != identifier:
            msg = _('item_{item}_in_file_{file}')\
                .format({'item': item_info.identifier, 'file': ver_file})
            raise ValueError(msg)

        if item_info.version != version:
            ver_str = util.version_string(item_info.version)
            msg = _('item_version_{ver}_in_file_{file}')\
                .format({'ver': ver_str, 'file': ver_file})
            raise ValueError(msg)

        if isinstance(item_info, ResourceInfo):
            self._register_info(self.resource_infos, identifier, item_info)
        elif isinstance(item_info, MappingInfo):
            self._register_info(self.mapping_infos, identifier, item_info)

    @staticmethod
    def _all_infos(infos: dict[str, VersionedItemInfo[VersionedType]]) \
        -> Iterable[VersionedType]:
        """
        ...........
        """
        for versioned_info in infos.values():
            for item_info in versioned_info.by_version.values():
                yield item_info

    def _report_missing(self) -> None:
        """
        Use logger to print information about items that are referenced but
        were not loaded.
        """
        def report_missing_dependency(info: ResourceInfo, dep: str) -> None:
            msg = _('no_dep_{resource}_{ver}_{dep}')\
                .format(dep=dep, resource=info.identifier,
                        ver=util.version_string(info.version))
            logging.error(msg)

        for resource_info in self._all_infos(self.resource_infos):
            for dep in resource_info.dependencies:
                if dep not in self.resource_infos:
                    report_missing_dependency(resource_info, dep)

        def report_missing_payload(info: MappingInfo, payload: str) -> None:
            msg = _('no_payload_{mapping}_{ver}_{payload}')\
                .format(mapping=info.identifier, payload=payload,
                        ver=util.version_string(info.version))
            logging.error(msg)

        for mapping_info in self._all_infos(self.mapping_infos):
            for payload in mapping_info.payloads.values():
                if payload not in self.resource_infos:
                    report_missing_payload(mapping_info, payload)

        def report_missing_mapping(info: ItemInfo,
                                   required_mapping: str) -> None:
            msg = _('no_mapping_{required_by}_{ver}_{required}')\
                .format(required_by=info.identifier, required=required_mapping,
                        ver=util.version_string(info.version))
            logging.error(msg)

        for item_info in (*self._all_infos(self.mapping_infos),
                          *self._all_infos(self.resource_infos)):
            for required in item_info.required_mappings:
                if required not in self.mapping_infos:
                    report_missing_mapping(item_info, required)

    def _finalize(self):
        """
        Initialize structures needed to serve queries. Called once after all
        data gets loaded.
        """
        for versioned_info in (*self.mapping_infos.values(),
                               *self.resource_infos.values()):
                versioned_info.known_versions.sort()

        for info in self._all_infos(self.mapping_infos):
            for pattern in info.payloads:
                try:
                    self.pattern_tree = \
                        self.pattern_tree.register(pattern, info)
                except Exception as e:
                    if flask.current_app._hydrilla_werror:
                        raise e from None
                    msg = _('couldnt_register_{mapping}_{ver}_{pattern}')\
                        .format(mapping=info.identifier, pattern=pattern,
                                ver=util.version_string(info.version))
                    logging.error(msg)

    def query(self, url: str) -> list[MappingInfo]:
        """
        Return a list of registered mappings that match url.

        If multiple versions of a mapping are applicable, only the most recent
        is included in the result.
        """
        collected: dict[str, MappingInfo] = {}
        for result_set in self.pattern_tree.search(url):
            for wrapped_mapping_info in result_set:
                info = wrapped_mapping_info.item
                previous = collected.get(info.identifier)
                if previous and previous.version > info.version:
                    continue

                collected[info.identifier] = info

        return list(collected.values())

bp = flask.Blueprint('bp', __package__)

class HydrillaApp(flask.Flask):
    """Flask app that implements a Hydrilla server."""
    def __init__(self, hydrilla_config: dict, flask_config: dict={}):
        """Create the Flask instance according to the configuration"""
        super().__init__(__package__, static_url_path='/',
                         static_folder=hydrilla_config['malcontent_dir'])
        self.config.update(flask_config)

        # https://stackoverflow.com/questions/9449101/how-to-stop-flask-from-initialising-twice-in-debug-mode
        if self.debug and os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
            return

        self.jinja_options = {
            **self.jinja_options,
            'extensions': [
                *self.jinja_options.get('extensions', []),
                'jinja2.ext.i18n'
            ]
        }

        self._hydrilla_project_url = hydrilla_config['hydrilla_project_url']
        self._hydrilla_port = hydrilla_config['port']
        self._hydrilla_werror = hydrilla_config.get('werror', False)

        if 'hydrilla_parent' in hydrilla_config:
            raise ValueError("Option 'hydrilla_parent' is not implemented.")

        malcontent_dir = Path(hydrilla_config['malcontent_dir']).resolve()
        with self.app_context():
            self._hydrilla_malcontent = Malcontent(malcontent_dir)

        self.register_blueprint(bp)

    def create_jinja_environment(self, *args, **kwargs) \
        -> flask.templating.Environment:
        """
        Flask's create_jinja_environment(), but tweaked to always include the
        'hydrilla_project_url' global variable and to install proper
        translations.
        """
        env = super().create_jinja_environment(*args, **kwargs) # type: ignore
        env.install_gettext_translations(make_translation())
        env.globals['hydrilla_project_url'] = self._hydrilla_project_url

        return env

    def run(self, *args, **kwargs):
        """
        Flask's run(), but tweaked to use the port from hydrilla configuration
        by default.
        """
        return super().run(*args, port=self._hydrilla_port, **kwargs)

def malcontent():
    return flask.current_app._hydrilla_malcontent

@bp.route('/')
def index():
    return flask.render_template('index.html')

identifier_json_re = re.compile(r'^([-0-9a-z.]+)\.json$')

def get_resource_or_mapping(item_type: str, identifier: str) -> Response:
    """
    Strip '.json' from 'identifier', look the item up and send its JSON
    description.
    """
    match = identifier_json_re.match(identifier)
    if not match:
        flask.abort(404)

    identifier = match.group(1)

    if item_type == 'resource':
        infos = malcontent().resource_infos
    else:
        infos = malcontent().mapping_infos

    versioned_info = infos.get(identifier)

    info = versioned_info and versioned_info.get_by_ver()
    if info is None:
        flask.abort(404)

    # no need for send_from_directory(); path is safe, constructed by us
    file_path = malcontent().malcontent_dir_path / item_type / info.path()
    return flask.send_file(open(file_path, 'rb'), mimetype='application/json')

@bp.route('/mapping/<string:identifier_dot_json>')
def get_newest_mapping(identifier_dot_json: str) -> Response:
    return get_resource_or_mapping('mapping', identifier_dot_json)

@bp.route('/resource/<string:identifier_dot_json>')
def get_newest_resource(identifier_dot_json: str) -> Response:
    return get_resource_or_mapping('resource', identifier_dot_json)

@bp.route('/query')
def query():
    url = flask.request.args['url']

    mapping_refs = [i.as_query_result() for i in malcontent().query(url)]
    result = {
        '$schema': 'https://hydrilla.koszko.org/schemas/api_query_result-1.schema.json',
        'mappings': mapping_refs,
        'generated_by': generated_by
    }

    return Response(json.dumps(result), mimetype='application/json')

@bp.route('/--help')
def mm_help():
    return start.get_help(click.Context(start_wsgi)) + '\n'

@bp.route('/--version')
def mm_version():
    prog_info = {'prog': 'Hydrilla', 'version': _version.version}
    return _('%(prog)s_%(version)s_license') % prog_info + '\n'

default_config_path = Path('/etc/hydrilla/config.json')
default_malcontent_dir = '/var/lib/hydrilla/malcontent'
default_project_url = 'https://hydrillabugs.koszko.org/projects/hydrilla/wiki'

@click.command(help=_('serve_hydrilla_packages_explain_wsgi_considerations'))
@click.option('-m', '--malcontent-dir',
              type=click.Path(exists=True, file_okay=False),
              help=_('directory_to_serve_from_overrides_config'))
@click.option('-h', '--hydrilla-project-url', type=click.STRING,
              help=_('project_url_to_display_overrides_config'))
@click.option('-p', '--port', type=click.INT,
              help=_('tcp_port_to_listen_on_overrides_config'))
@click.option('-c', '--config', 'config_path',
              type=click.Path(exists=True, dir_okay=False, resolve_path=True),
              help=_('path_to_config_file_explain_default'))
@click.version_option(version=_version.version, prog_name='Hydrilla',
                      message=_('%(prog)s_%(version)s_license'),
                      help=_('version_printing'))
def start(malcontent_dir: Optional[str], hydrilla_project_url: Optional[str],
          port: Optional[int], config_path: Optional[str]) -> None:
    """
    Run a development Hydrilla server.

    This command is meant to be the entry point of hydrilla command exported by
    this package.
    """
    if config_path is None:
        hydrilla_config = config.load()
    else:
        hydrilla_config = config.load(config_paths=[Path(config_path)])

    if malcontent_dir is not None:
        hydrilla_config['malcontent_dir'] = str(Path(malcontent_dir).resolve())

    if hydrilla_project_url is not None:
        hydrilla_config['hydrilla_project_url'] = hydrilla_project_url

    if port is not None:
        hydrilla_config['port'] = port

    for opt in ('malcontent_dir', 'hydrilla_project_url', 'port'):
        if opt not in hydrilla_config:
            raise ValueError(_('config_option_{}_not_supplied').format(opt))

    HydrillaApp(hydrilla_config).run()

@click.command(help=_('serve_hydrilla_packages_wsgi_help'),
               context_settings={
                   'ignore_unknown_options': True,
                   'allow_extra_args': True
               })
@click.version_option(version=_version.version, prog_name='Hydrilla',
                      message=_('%(prog)s_%(version)s_license'),
                      help=_('version_printing'))
def start_wsgi() -> flask.Flask:
    """
    Create application object for use in WSGI deployment.

    This command Also handles --help and --version options in case it gets
    called outside WSGI environment.
    """
    return HydrillaApp(click.get_current_context().obj or config.load())