summaryrefslogtreecommitdiff
path: root/src/hydrilla/proxy/simple_dependency_satisfying.py
blob: d03c86e5f0005504139b1547304c3dd6c5283022 (about) (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
# SPDX-License-Identifier: GPL-3.0-or-later

# Haketilo proxy payloads dependency resolution.
#
# This file is part of Hydrilla&Haketilo.
#
# Copyright (C) 2022 Wojtek Kosior
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
#
# You should have received a copy of the GNU 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 of this
# code in a proprietary program, I am not going to enforce this in
# court.

"""
This module contains logic to construct the dependency graph of Haketilo
packages and to perform dependency resolution.

The approach taken here is a very simplified one. Hopefully, this will at some
point be replaced by a solution based on some SAT solver.
"""

# Enable using with Python 3.7.
from __future__ import annotations

import dataclasses as dc
import typing as t
import functools as ft

from immutables import Map

from ..exceptions import HaketiloException
from .. import item_infos
from .. import url_patterns


@dc.dataclass(frozen=True)
class ImpossibleSituation(HaketiloException):
    bad_mapping_identifiers: frozenset[str]


@dc.dataclass(frozen=True)
class MappingRequirement:
    identifier: str

    def is_fulfilled_by(self, info: item_infos.MappingInfo) -> bool:
        return True

@dc.dataclass(frozen=True)
class MappingRepoRequirement(MappingRequirement):
    repo: str

    def is_fulfilled_by(self, info: item_infos.MappingInfo) -> bool:
        return info.repo == self.repo

@dc.dataclass(frozen=True)
class MappingVersionRequirement(MappingRequirement):
    version_info: item_infos.MappingInfo

    def __post_init__(self):
        assert self.version_info.identifier == self.identifier

    def is_fulfilled_by(self, info: item_infos.MappingInfo) -> bool:
        return info == self.version_info


@dc.dataclass(frozen=True)
class ResourceVersionRequirement:
    mapping_identifier: str
    version_info:       item_infos.ResourceInfo

    def is_fulfilled_by(self, info: item_infos.ResourceInfo) -> bool:
        return info == self.version_info


@dc.dataclass
class ComputedPayload:
    mapping_identifier: str

    resources: list[item_infos.ResourceInfo] = dc.field(default_factory=list)

    allows_eval:        bool = False
    allows_cors_bypass: bool = False

@dc.dataclass
class MappingChoice:
    info:                 item_infos.MappingInfo
    required:             bool                               = False
    mapping_dependencies: t.Sequence[item_infos.MappingInfo] = ()

    payloads: dict[url_patterns.ParsedPattern, ComputedPayload] = \
        dc.field(default_factory=dict)


MappingsGraph = t.Union[
    t.Mapping[str, set[str]],
    t.Mapping[str, frozenset[str]]
]

def _mark_mappings(
        identifier:      str,
        mappings_graph:  MappingsGraph,
        marked_mappings: set[str]
) -> None:
    if identifier in marked_mappings:
        return

    marked_mappings.add(identifier)

    for next_mapping in mappings_graph.get(identifier, ()):
            _mark_mappings(next_mapping, mappings_graph, marked_mappings)


ComputedChoices = dict[str, MappingChoice]

def _compute_inter_mapping_deps(choices: ComputedChoices) \
    -> dict[str, frozenset[str]]:
    mapping_deps: dict[str, frozenset[str]] = {}

    for mapping_choice in choices.values():
        specs_to_resolve = [*mapping_choice.info.required_mappings]

        for computed_payload in mapping_choice.payloads.values():
            for resource_info in computed_payload.resources:
                specs_to_resolve.extend(resource_info.required_mappings)

        depended = frozenset(spec.identifier for spec in specs_to_resolve)
        mapping_deps[mapping_choice.info.identifier] = depended

    return mapping_deps

@dc.dataclass(frozen=True)
class _ComputationData:
    resources_map: item_infos.MultirepoResourceInfoMap
    mappings_map:  item_infos.MultirepoMappingInfoMap

    mappings_to_reqs: t.Mapping[str, t.Sequence[MappingRequirement]]

    mappings_resources_to_reqs: t.Mapping[
        tuple[str, str],
        t.Sequence[ResourceVersionRequirement]
    ]

    def _satisfy_payload_resource_rec(
            self,
            resource_identifier: str,
            processed_resources: set[str],
            computed_payload:    ComputedPayload
    ) -> t.Optional[ComputedPayload]:
        if resource_identifier in processed_resources:
            # We forbid circular dependencies.
            return None

        multirepo_info = self.resources_map.get(resource_identifier)
        if multirepo_info is None:
            return None

        key = (computed_payload.mapping_identifier, resource_identifier)
        resource_reqs = self.mappings_resources_to_reqs.get(key)

        if resource_reqs is None:
            info = multirepo_info.default_info
        else:
            found = False
            # From newest to oldest version.
            for info in multirepo_info.get_all(reverse_versions=True):
                if all(req.is_fulfilled_by(info) for req in resource_reqs):
                    found = True
                    break

            if not found:
                return None

        if info in computed_payload.resources:
            return computed_payload

        processed_resources.add(resource_identifier)

        if info.allows_eval:
            computed_payload.allows_eval = True

        if info.allows_cors_bypass:
            computed_payload.allows_cors_bypass = True

        for dependency_spec in info.dependencies:
            if self._satisfy_payload_resource_rec(
                    dependency_spec.identifier,
                    processed_resources,
                    computed_payload
            ) is None:
                return None

        processed_resources.remove(resource_identifier)

        computed_payload.resources.append(info)

        return computed_payload

    def _satisfy_payload_resource(
            self,
            mapping_identifier:  str,
            resource_identifier: str
    ) -> t.Optional[ComputedPayload]:
        return self._satisfy_payload_resource_rec(
            resource_identifier,
            set(),
            ComputedPayload(mapping_identifier)
        )

    def _compute_best_choices(self) -> ComputedChoices:
        choices = ComputedChoices()

        for multirepo_info in self.mappings_map.values():
            choice: t.Optional[MappingChoice] = None

            reqs = self.mappings_to_reqs.get(multirepo_info.identifier)
            if reqs is None:
                choice = MappingChoice(multirepo_info.default_info)
            else:
                # From newest to oldest version.
                for info in multirepo_info.get_all(reverse_versions=True):
                    if all(req.is_fulfilled_by(info) for req in reqs):
                        choice = MappingChoice(info=info, required=True)
                        break

                if choice is None:
                    continue

            failure = False

            for pattern, resource_spec in choice.info.payloads.items():
                computed_payload = self._satisfy_payload_resource(
                    mapping_identifier  = choice.info.identifier,
                    resource_identifier = resource_spec.identifier
                )
                if computed_payload is None:
                    failure = True
                    break

                if choice.info.allows_eval:
                    computed_payload.allows_eval = True

                if choice.info.allows_cors_bypass:
                    computed_payload.allows_cors_bypass = True

                choice.payloads[pattern] = computed_payload

            if not failure:
                choices[choice.info.identifier] = choice

        return choices

    def compute_payloads(self) -> ComputedChoices:
        choices = self._compute_best_choices()

        mapping_deps = _compute_inter_mapping_deps(choices)

        reverse_deps: dict[str, set[str]] = {}

        for depending, depended_set in mapping_deps.items():
            for depended in depended_set:
                reverse_deps.setdefault(depended, set()).add(depending)

        bad_mappings: set[str] = set()

        for depended_identifier in reverse_deps.keys():
            if depended_identifier not in choices:
                _mark_mappings(depended_identifier, reverse_deps, bad_mappings)

        bad_required_mappings: list[str] = []

        for identifier in self.mappings_to_reqs.keys():
            if identifier in bad_mappings or identifier not in choices:
                bad_required_mappings.append(identifier)

        if len(bad_required_mappings) > 0:
            raise ImpossibleSituation(frozenset(bad_required_mappings))

        for identifier in bad_mappings:
            choices.pop(identifier, None)

        required_mappings: set[str] = set()

        for identifier in self.mappings_to_reqs.keys():
            _mark_mappings(identifier, mapping_deps, required_mappings)

        for identifier in required_mappings:
            choices[identifier].required = True

        for mapping_choice in choices.values():
            depended_set = mapping_deps[mapping_choice.info.identifier]
            mapping_choice.mapping_dependencies = \
                tuple(choices[identifier].info for identifier in depended_set)

        return choices

def compute_payloads(
        resources:             t.Iterable[item_infos.ResourceInfo],
        mappings:              t.Iterable[item_infos.MappingInfo],
        mapping_requirements:  t.Iterable[MappingRequirement],
        resource_requirements: t.Iterable[ResourceVersionRequirement]
) -> ComputedChoices:
    resources_map: item_infos.MultirepoResourceInfoMap = \
        ft.reduce(item_infos.register_in_multirepo_map, resources, Map())
    mappings_map: item_infos.MultirepoMappingInfoMap = \
        ft.reduce(item_infos.register_in_multirepo_map, mappings, Map())

    mappings_to_reqs: dict[str, list[MappingRequirement]] = {}
    for mapping_req in mapping_requirements:
        mappings_to_reqs.setdefault(mapping_req.identifier, [])\
            .append(mapping_req)

    mappings_resources_to_reqs: dict[
        tuple[str, str],
        list[ResourceVersionRequirement]
    ] = {}
    for resource_req in resource_requirements:
        info = resource_req.version_info
        key = (resource_req.mapping_identifier, info.identifier)
        mappings_resources_to_reqs.setdefault(key, [])\
            .append(resource_req)

    return _ComputationData(
        mappings_map               = mappings_map,
        resources_map              = resources_map,
        mappings_to_reqs           = mappings_to_reqs,
        mappings_resources_to_reqs = mappings_resources_to_reqs
    ).compute_payloads()