Project

General

Profile

Download (9.48 KB) Statistics
| Branch: | Tag: | Revision:

haketilo / common / patterns_query_tree.js @ ad69f9c8

1
/**
2
 * This file is part of Haketilo.
3
 *
4
 * Function: Data structure to query items by URL patterns.
5
 *
6
 * Copyright (C) 2021 Wojtek Kosior
7
 *
8
 * This program is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU General Public License as published by
10
 * the Free Software Foundation, either version 3 of the License, or
11
 * (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * As additional permission under GNU GPL version 3 section 7, you
19
 * may distribute forms of that code without the copy of the GNU
20
 * GPL normally required by section 4, provided you include this
21
 * license notice and, in case of non-source distribution, a URL
22
 * through which recipients can access the Corresponding Source.
23
 * If you modify file(s) with this exception, you may extend this
24
 * exception to your version of the file(s), but you are not
25
 * obligated to do so. If you do not wish to do so, delete this
26
 * exception statement from your version.
27
 *
28
 * As a special exception to the GPL, any HTML file which merely
29
 * makes function calls to this code, and for that purpose
30
 * includes it by reference shall be deemed a separate work for
31
 * copyright law purposes. If you modify this code, you may extend
32
 * this exception to your version of the code, but you are not
33
 * obligated to do so. If you do not wish to do so, delete this
34
 * exception statement from your version.
35
 *
36
 * You should have received a copy of the GNU General Public License
37
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
38
 *
39
 * I, Wojtek Kosior, thereby promise not to sue for violation of this file's
40
 * license. Although I request that you do not make use of this code in a
41
 * proprietary program, I am not going to enforce this in court.
42
 */
43

    
44
// TODO! Modify the code to use `Object.create(null)` instead of `{}`.
45

    
46
#FROM common/patterns.js IMPORT deconstruct_url
47

    
48
/* "Pattern Tree" is how we refer to the data structure used for querying
49
 * Haketilo patterns. Those look like 'https://*.example.com/ab/***'. The goal
50
 * is to make it possible for given URL to quickly retrieve all known patterns
51
 * that match it.
52
 */
53
const pattern_tree_make = () => ({})
54
#EXPORT  pattern_tree_make  AS make
55

    
56
function empty_node() {
57
    return {
58
	wildcard_matches: [null, null, null],
59
	literal_match:    null,
60
	children:         {}
61
    };
62
}
63

    
64
function is_empty_node(tree_node) {
65
    const children = tree_node.children;
66
    for (const key in children) {
67
	if (children.hasOwnProperty(key))
68
	    return false;
69
    }
70

    
71
    if (tree_node.wildcard_matches.reduce((a, b) => b && a !== null, 1))
72
	return false;
73

    
74
    return tree_node.literal_match === null;
75
}
76

    
77
const is_wildcard = segment => ["*", "**", "***"].lastIndexOf(segment) >= 0;
78

    
79
/*
80
 * Yields all matches of this segments sequence against the tree that starts at
81
 * this node. Results are produces in order from greatest to lowest pattern
82
 * specificity.
83
 */
84
function* search_sequence(tree_node, segments)
85
{
86
    const nodes = [tree_node];
87

    
88
    for (const segment of segments) {
89
	const next_node = nodes[nodes.length - 1].children[segment];
90
	if (next_node === undefined)
91
	    break;
92

    
93
	nodes.push(next_node);
94
    }
95

    
96
    const nsegments = segments.length;
97

    
98
    const conds = [
99
	/* literal pattern match */
100
	() => nodes.length     == nsegments,
101
	/* wildcard pattern matches */
102
	() => nodes.length + 1 == nsegments && segments[nsegments - 1] != "*",
103
	() => nodes.length + 1 <  nsegments,
104
	() => nodes.length + 1 != nsegments || segments[nsegments - 1] != "***"
105
    ];
106

    
107
    while (nodes.length) {
108
	const node = nodes.pop();
109
	const items = [node.literal_match, ...node.wildcard_matches];
110

    
111
	for (let i = 0; i < 4; i++) {
112
	    if (items[i] !== null && conds[i]())
113
		yield items[i];
114
	}
115
    }
116
}
117

    
118
/*
119
 * Make item queryable through (this branch of) the Pattern Tree or remove its
120
 * path from there.
121
 *
122
 * item_modifier should be a function that accepts 1 argument, the item stored
123
 * in the tree (or `null` if there wasn't any item there), and returns an item
124
 * that should be used in place of the first one. It is also legal for it to
125
 * return the same item modifying it first. If it returns `null`, it means the
126
 * item should be deleted from the Tree.
127
 *
128
 * If there was not yet any item associated with the tree path designated by
129
 * segments and value returned by item_modifier is not `null`, make the value
130
 * queryable by this path.
131
 */
132
function modify_sequence(tree_node, segments, item_modifier)
133
{
134
    const nodes = [tree_node];
135
    let removed = true;
136

    
137
    for (var current_segment of segments) {
138
	const child = tree_node.children[current_segment] || empty_node();
139
	tree_node.children[current_segment] = child;
140
	tree_node = child;
141
	nodes.push(tree_node);
142
    }
143

    
144
    tree_node.literal_match = item_modifier(tree_node.literal_match);
145
    if (tree_node.literal_match !== null)
146
	removed = false;
147

    
148
    let i = segments.length;
149

    
150
    if (is_wildcard(current_segment)) {
151
	const asterisks = current_segment.length - 1;
152
	const wildcards = nodes[i - 1].wildcard_matches;
153
	wildcards[asterisks] = item_modifier(wildcards[asterisks]);
154
	if (wildcards[asterisks] !== null)
155
	    removed = false;
156
    }
157

    
158
    while (!removed)
159
	return;
160

    
161
    while (i > 0) {
162
	tree_node = nodes[i--];
163
	if (is_empty_node(tree_node))
164
	    delete nodes[i].children[segments[i]];
165
    }
166
}
167

    
168
/* Helper function for modify_tree(). */
169
function modify_path(tree_node, deco, item_modifier)
170
{
171
    tree_node = tree_node || empty_node();
172
    modify_sequence(tree_node, deco.path, item_modifier);
173
    return is_empty_node(tree_node) ? null : tree_node;
174
}
175

    
176
/* Helper function for modify_tree(). */
177
function modify_domain(tree_node, deco, item_modifier)
178
{
179
    const path_modifier = branch => modify_path(branch, deco, item_modifier);
180
    tree_node = tree_node || empty_node();
181
    /* We need an array of domain labels ordered most-significant-first. */
182
    modify_sequence(tree_node, [...deco.domain].reverse(), path_modifier);
183
    return is_empty_node(tree_node) ? null : tree_node;
184
}
185

    
186
/* Helper function for pattern_tree_register() and pattern_tree_deregister(). */
187
function modify_tree(patterns_by_proto, pattern, item_modifier)
188
{
189
    /*
190
     * We pass 'false' to disable length limits on URL parts. Length limits are
191
     * mostly useful in case of iteration over all patterns matching given URL.
192
     * Here we don't do that.
193
     */
194
    const deco = deconstruct_url(pattern, false);
195

    
196
    let tree_for_proto = patterns_by_proto[deco.proto];
197

    
198
    tree_for_proto = deco.domain === undefined ?
199
	modify_path(tree_for_proto, deco, item_modifier) :
200
	modify_domain(tree_for_proto, deco, item_modifier);
201

    
202
    patterns_by_proto[deco.proto] = tree_for_proto;
203
    if (tree_for_proto === null)
204
	delete patterns_by_proto[deco.proto];
205
}
206

    
207
/*
208
 * Make item queryable through the Pattern Tree that starts with the protocols
209
 * dictionary object passed in the first argument.
210
 */
211
function pattern_tree_register(patterns_by_proto, pattern, item_name, item)
212
{
213
    const key_prefix = pattern[pattern.length - 1] === '/' ? '/' : '_';
214
    item_name = key_prefix + item_name;
215
    const add_item = obj => Object.assign(obj || {}, {[item_name]: item});
216
    modify_tree(patterns_by_proto, pattern, add_item);
217
}
218
#EXPORT  pattern_tree_register  AS register
219

    
220
/* Helper function for pattern_tree_deregister(). */
221
function _remove_item(obj, item_name)
222
{
223
    obj = obj || {};
224
    delete obj[item_name];
225
    for (const key in obj)
226
	return obj;
227
    return null;
228
}
229

    
230
/*
231
 * Remove registered item from the Pattern Tree that starts with the protocols
232
 * dictionary object passed in the first argument. The remaining 2 arguments
233
 * should be pattern and name that have been earlier passed to
234
 * pattern_tree_register().
235
 */
236
function pattern_tree_deregister(patterns_by_proto, pattern, item_name)
237
{
238
    const key_prefix = pattern[pattern.length - 1] === '/' ? '/' : '_';
239
    item_name = key_prefix + item_name;
240
    const remove_item = obj => _remove_item(obj, item_name);
241
    modify_tree(patterns_by_proto, pattern, remove_item);
242
}
243
#EXPORT  pattern_tree_deregister  AS deregister
244

    
245
/*
246
 * Yield registered items that match url. Each yielded value is an object with
247
 * key being matched item names and values being the items. One such object
248
 * shall contain all items matched with given pattern specificity. Objects are
249
 * yielded in order from greatest to lowest pattern specificity.
250
 */
251
function* pattern_tree_search(patterns_by_proto, url)
252
{
253
    const deco = deconstruct_url(url, false);
254

    
255
    const tree_for_proto = patterns_by_proto[deco.proto] || empty_node();
256
    let by_path = [tree_for_proto];
257

    
258
    /* We need an array of domain labels ordered most-significant-first. */
259
    if (deco.domain !== undefined)
260
	by_path = search_sequence(tree_for_proto, [...deco.domain].reverse());
261

    
262
    for (const path_tree of by_path) {
263
	for (const match_obj of search_sequence(path_tree, deco.path)) {
264
	    let result_obj_slash    = null;
265
	    let result_obj_no_slash = null;
266

    
267
	    for (const [key, item] of Object.entries(match_obj)) {
268
		if (deco.trailing_slash && key[0] === '/') {
269
		    result_obj_slash = result_obj_slash || {};
270
		    result_obj_slash[key.substring(1)] = item;
271
		} else if (key[0] !== '/') {
272
		    result_obj_no_slash = result_obj_no_slash || {};
273
		    result_obj_no_slash[key.substring(1)] = item;
274
		}
275
	    }
276

    
277
	    if (deco.trailing_slash && result_obj_slash)
278
		yield result_obj_slash;
279

    
280
	    if (result_obj_no_slash)
281
		yield result_obj_no_slash;
282
	}
283
    }
284
}
285
#EXPORT  pattern_tree_search  AS search
(8-8/10)