Project

General

Profile

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

haketilo / common / indexeddb.js @ 26e4800d

1
/**
2
 * This file is part of Haketilo.
3
 *
4
 * Function: Facilitate use of IndexedDB within Haketilo.
5
 *
6
 * Copyright (C) 2021 Wojtek Kosior <koszko@koszko.org>
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
#IMPORT common/entities.js
45
#IMPORT common/broadcast.js
46

    
47
let initial_data = (
48
#IF UNIT_TEST
49
    {}
50
#ELSE
51
#INCLUDE default_settings.json
52
#ENDIF
53
);
54

    
55
/* Update when changes are made to database schema. Must have 3 elements */
56
const db_version = [1, 0, 0];
57

    
58
const nr_reductor = ([i, s], num) => [i - 1, s + num * 1024 ** i];
59
const version_nr = ver => ver.slice(0, 3).reduce(nr_reductor, [2, 0])[1];
60

    
61
const stores = 	[
62
    ["files",     {keyPath: "hash_key"}],
63
    ["file_uses", {keyPath: "hash_key"}],
64
    ["resource",  {keyPath: "identifier"}],
65
    ["mapping",   {keyPath: "identifier"}],
66
    ["settings",  {keyPath: "name"}],
67
    ["blocking",  {keyPath: "pattern"}],
68
    ["repos",     {keyPath: "url"}]
69
];
70

    
71
let db = null;
72

    
73
/* Generate a Promise that resolves when an IndexedDB request succeeds. */
74
async function wait_request(idb_request)
75
{
76
    let resolve, reject;
77
    const waiter = new Promise((...cbs) => [resolve, reject] = cbs);
78
    [idb_request.onsuccess, idb_request.onerror] = [resolve, reject];
79
    return waiter;
80
}
81

    
82
/* asynchronous wrapper for IDBObjectStore's get() method. */
83
async function idb_get(transaction, store_name, key)
84
{
85
    const req = transaction.objectStore(store_name).get(key);
86
    return (await wait_request(req)).target.result;
87
}
88
#EXPORT idb_get
89

    
90
/* asynchronous wrapper for IDBObjectStore's put() method. */
91
async function idb_put(transaction, store_name, object)
92
{
93
    return wait_request(transaction.objectStore(store_name).put(object));
94
}
95

    
96
/* asynchronous wrapper for IDBObjectStore's delete() method. */
97
async function idb_del(transaction, store_name, key)
98
{
99
    return wait_request(transaction.objectStore(store_name).delete(key));
100
}
101

    
102
async function perform_upgrade(event) {
103
    const opened_db = event.target.result;
104

    
105
    /* When we move to a new database schema, we will add upgrade logic here. */
106
    if (event.oldVersion > 0)
107
	throw "bad db version: " + event.oldVersion;
108

    
109
    let store;
110
    for (const [store_name, key_mode] of stores)
111
	store = opened_db.createObjectStore(store_name, key_mode);
112

    
113
    const ctx = make_context(store.transaction, initial_data.files);
114
    await _save_items(initial_data.resources, initial_data.mappings, ctx);
115

    
116
    return opened_db;
117
}
118

    
119
/* Open haketilo database, asynchronously return an IDBDatabase object. */
120
async function get_db() {
121
    if (db)
122
	return db;
123

    
124
    let resolve, reject;
125
    const waiter = new Promise((...cbs) => [resolve, reject] = cbs);
126

    
127
    const request = indexedDB.open("haketilo", version_nr(db_version));
128
    request.onsuccess       = ev => resolve(ev.target.result);
129
    request.onerror         = ev => reject("db error: " + ev.target.errorCode);
130
    request.onupgradeneeded = ev => perform_upgrade(ev).then(resolve, reject);
131

    
132
    const opened_db = await waiter;
133

    
134
    if (db)
135
	opened_db.close();
136
    else
137
	db = opened_db;
138

    
139
    return db;
140
}
141
#EXPORT  get_db  AS get
142

    
143
/* Helper function used by make_context(). */
144
function reject_discard(context)
145
{
146
    broadcast.discard(context.sender);
147
    broadcast.close(context.sender);
148
    context.reject();
149
}
150

    
151
/* Helper function used by make_context(). */
152
function resolve_flush(context)
153
{
154
    broadcast.close(context.sender);
155
    context.resolve();
156
}
157

    
158
/* Helper function used by start_items_transaction() and get_db(). */
159
function make_context(transaction, files)
160
{
161
    const sender = broadcast.sender_connection();
162

    
163
    files = files || {};
164
    let resolve, reject;
165
    const result = new Promise((...cbs) => [resolve, reject] = cbs);
166

    
167
    const context =
168
	  {sender, transaction, resolve, reject, result, files, file_uses: {}};
169

    
170
    transaction.oncomplete = () => resolve_flush(context);
171
    transaction.onerror = () => reject_discard(context);
172

    
173
    return context;
174
}
175

    
176
/*
177
 * item_store_names should be an array with either string "mapping", string
178
 * "resource" or both. files should be an object with values being contents of
179
 * files that are to be possibly saved in this transaction and keys of the form
180
 * `sha256-<file's-sha256-sum>`.
181
 *
182
 * Returned is a context object wrapping the transaction and handling the
183
 * counting of file references in IndexedDB.
184
 */
185
async function start_items_transaction(item_store_names, files)
186
{
187
    const db = await get_db();
188
    const scope = [...item_store_names, "files", "file_uses"];
189
    return make_context(db.transaction(scope, "readwrite"), files);
190
}
191
#EXPORT start_items_transaction
192

    
193
async function incr_file_uses(context, file_ref, by=1)
194
{
195
    const hash_key = file_ref.hash_key;
196
    let uses = context.file_uses[hash_key];
197
    if (uses === undefined) {
198
	uses = await idb_get(context.transaction, "file_uses", hash_key);
199
	if (uses)
200
	    [uses.new, uses.initial] = [false, uses.uses];
201
	else
202
	    uses = {hash_key, uses: 0, new: true, initial: 0};
203

    
204
	context.file_uses[hash_key] = uses;
205
    }
206

    
207
    uses.uses = uses.uses + by;
208
}
209

    
210
const decr_file_uses = (ctx, file_ref) => incr_file_uses(ctx, file_ref, -1);
211

    
212
async function finalize_transaction(context)
213
{
214
    for (const uses of Object.values(context.file_uses)) {
215
	if (uses.uses < 0)
216
	    console.error("internal error: uses < 0 for file " + uses.hash_key);
217

    
218
	const is_new       = uses.new;
219
	const initial_uses = uses.initial;
220
	const hash_key     = uses.hash_key;
221

    
222
	delete uses.new;
223
	delete uses.initial;
224

    
225
	if (uses.uses < 1) {
226
	    if (!is_new) {
227
		idb_del(context.transaction, "file_uses", hash_key);
228
		idb_del(context.transaction, "files",     hash_key);
229
	    }
230

    
231
	    continue;
232
	}
233

    
234
	if (uses.uses === initial_uses)
235
	    continue;
236

    
237
	idb_put(context.transaction, "file_uses", uses);
238

    
239
	if (initial_uses > 0)
240
	    continue;
241

    
242
	const file = context.files[hash_key];
243
	if (file === undefined) {
244
	    context.transaction.abort();
245
	    throw "file not present: " + hash_key;
246
	}
247

    
248
	idb_put(context.transaction, "files", {hash_key, contents: file});
249
    }
250

    
251
    return context.result;
252
}
253
#EXPORT finalize_transaction
254

    
255
/*
256
 * How a sample data argument to the function below might look like:
257
 *
258
 * data = {
259
 *     resources: {
260
 *         "resource1": {
261
 *             "1": {
262
 *                 // some stuff
263
 *             },
264
 *             "1.1": {
265
 *                 // some stuff
266
 *             }
267
 *         },
268
 *         "resource2": {
269
 *             "0.4.3": {
270
 *                 // some stuff
271
 *             }
272
 *         },
273
 *     },
274
 *     mappings: {
275
 *         "mapping1": {
276
 *             "2": {
277
 *                 // some stuff
278
 *             }
279
 *         },
280
 *         "mapping2": {
281
 *             "0.1": {
282
 *                 // some stuff
283
 *             }
284
 *         },
285
 *     },
286
 *     files: {
287
 *         "sha256-f9444510dc7403e41049deb133f6892aa6a63c05591b2b59e4ee5b234d7bbd99": "console.log(\"hello\");\n",
288
 *         "sha256-b857cd521cc82fff30f0d316deba38b980d66db29a5388eb6004579cf743c6fd": "console.log(\"bye\");"
289
 *     }
290
 * }
291
 */
292
async function save_items(data)
293
{
294
    const item_store_names = ["resource", "mapping"];
295
    const context = await start_items_transaction(item_store_names, data.files);
296

    
297
    return _save_items(data.resources, data.mappings, context);
298
}
299
#EXPORT save_items
300

    
301
async function _save_items(resources, mappings, context)
302
{
303
    resources = Object.values(resources || {}).map(entities.get_newest);
304
    mappings  = Object.values(mappings  || {}).map(entities.get_newest);
305

    
306
    for (const item of resources.concat(mappings))
307
	await save_item(item, context);
308

    
309
    await finalize_transaction(context);
310
}
311

    
312
/*
313
 * Save given definition of a resource/mapping to IndexedDB. If the definition
314
 * (passed as `item`) references files that are not already present in
315
 * IndexedDB, those files should be provided as values of the `files' object
316
 * used to create the transaction context.
317
 *
318
 * context should be one returned from start_items_transaction() and should be
319
 * later passed to finalize_transaction() so that files depended on are added to
320
 * IndexedDB and files that are no longer depended on after this operation are
321
 * removed from IndexedDB.
322
 */
323
async function save_item(item, context)
324
{
325
    for (const file_ref of entities.get_files(item))
326
	await incr_file_uses(context, file_ref);
327

    
328
    broadcast.prepare(context.sender, `idb_changes_${item.type}`,
329
		      item.identifier);
330
    await _remove_item(item.type, item.identifier, context, false);
331
    await idb_put(context.transaction, item.type, item);
332
}
333
#EXPORT save_item
334

    
335
/* Helper function used by remove_item() and save_item(). */
336
async function _remove_item(store_name, identifier, context)
337
{
338
    const item = await idb_get(context.transaction, store_name, identifier);
339
    if (item !== undefined) {
340
	for (const file_ref of entities.get_files(item))
341
	    await decr_file_uses(context, file_ref);
342
    }
343
}
344

    
345
/*
346
 * Remove definition of a resource/mapping from IndexedDB.
347
 *
348
 * context should be one returned from start_items_transaction() and should be
349
 * later passed to finalize_transaction() so that files depended on are added to
350
 * IndexedDB and files that are no longer depended on after this operation are
351
 * removed from IndexedDB.
352
 */
353
async function remove_item(store_name, identifier, context)
354
{
355
    broadcast.prepare(context.sender, `idb_changes_${store_name}`, identifier);
356
    await _remove_item(store_name, identifier, context);
357
    await idb_del(context.transaction, store_name, identifier);
358
}
359

    
360
const remove_resource = (id, ctx) => remove_item("resource", id, ctx);
361
#EXPORT remove_resource
362

    
363
const remove_mapping = (id, ctx) => remove_item("mapping",  id, ctx);
364
#EXPORT remove_mapping
365

    
366
/* Function to retrieve all items from a given store. */
367
async function get_all(store_name)
368
{
369
    const transaction = (await get_db()).transaction([store_name]);
370
    const all_req = transaction.objectStore(store_name).getAll();
371

    
372
    return (await wait_request(all_req)).target.result;
373
}
374
#EXPORT get_all
375

    
376
/*
377
 * A simplified kind of transaction for modifying stores without special
378
 * inter-store integrity constraints ("settings", "blocking", "repos").
379
 */
380
async function start_simple_transaction(store_name)
381
{
382
    const db = await get_db();
383
    return make_context(db.transaction(store_name, "readwrite"), {});
384
}
385

    
386
/* Functions to access the "settings" store. */
387
async function set_setting(name, value)
388
{
389
    const context = await start_simple_transaction("settings");
390
    broadcast.prepare(context.sender, "idb_changes_settings", name);
391
    await idb_put(context.transaction, "settings", {name, value});
392
    return finalize_transaction(context);
393
}
394
#EXPORT set_setting
395

    
396
async function get_setting(name)
397
{
398
    const transaction = (await get_db()).transaction("settings");
399
    return ((await idb_get(transaction, "settings", name)) || {}).value;
400
}
401
#EXPORT get_setting
402

    
403
/* Functions to access the "blocking" store. */
404
async function set_allowed(pattern, allow=true)
405
{
406
    const context = await start_simple_transaction("blocking");
407
    broadcast.prepare(context.sender, "idb_changes_blocking", pattern);
408
    if (allow === null)
409
	await idb_del(context.transaction, "blocking", pattern);
410
    else
411
	await idb_put(context.transaction, "blocking", {pattern, allow});
412
    return finalize_transaction(context);
413
}
414
#EXPORT set_allowed
415

    
416
const set_disallowed = pattern => set_allowed(pattern, false);
417
#EXPORT set_disallowed
418

    
419
const set_default_allowing = pattern => set_allowed(pattern, null);
420
#EXPORT set_default_allowing
421

    
422
async function get_allowing(pattern)
423
{
424
    const transaction = (await get_db()).transaction("blocking");
425
    return ((await idb_get(transaction, "blocking", pattern)) || {}).allow;
426
}
427
#EXPORT get_allowing
428

    
429
/* Functions to access the "repos" store. */
430
async function set_repo(url, remove=false)
431
{
432
    const context = await start_simple_transaction("repos");
433
    broadcast.prepare(context.sender, "idb_changes_repos", url);
434
    if (remove)
435
	await idb_del(context.transaction, "repos", url);
436
    else
437
	await idb_put(context.transaction, "repos", {url});
438
    return finalize_transaction(context);
439
}
440
#EXPORT set_repo
441

    
442
const del_repo = url => set_repo(url, true);
443
#EXPORT del_repo
444

    
445
const get_repos = () => get_all("repos").then(list => list.map(obj => obj.url));
446
#EXPORT get_repos
447

    
448
/* Callback used when listening to broadcasts while tracking db changes. */
449
async function track_change(tracking, key)
450
{
451
    const transaction = (await get_db()).transaction([tracking.store_name]);
452
    const new_val = await idb_get(transaction, tracking.store_name, key);
453

    
454
    tracking.onchange({key, new_val});
455
}
456

    
457
/*
458
 * Monitor changes to `store_name` IndexedDB object store.
459
 *
460
 * `store_name` should be either "resource", "mapping", "settings", "blocking"
461
 * or "repos".
462
 *
463
 * `onchange` should be a callback that will be called when an item is added,
464
 * modified or removed from the store. The callback will be passed an object
465
 * representing the change as its first argument. This object will have the
466
 * form:
467
 * {
468
 *     key: "the identifier of modified resource/mapping or settings key",
469
 *     new_val: undefined // `undefined` if item removed, item object otherwise
470
 * }
471
 *
472
 * Returns a [tracking, all_current_items] array where `tracking` is an object
473
 * that can be later passed to untrack() to stop tracking changes and
474
 * `all_current_items` is an array of items currently present in the object
475
 * store.
476
 *
477
 * It is possible that `onchange` gets spuriously fired even when an item is not
478
 * actually modified or that it only gets called once after multiple quick
479
 * changes to an item.
480
 */
481
async function start_tracking(store_name, onchange)
482
{
483
    const tracking = {store_name, onchange};
484
    tracking.listener =
485
	broadcast.listener_connection(msg => track_change(tracking, msg[1]));
486
    broadcast.subscribe(tracking.listener, `idb_changes_${store_name}`);
487

    
488
    return [tracking, await get_all(store_name)];
489
}
490

    
491
const track = {};
492
const trackable = ["resource", "mapping", "settings", "blocking", "repos"];
493
for (const store_name of trackable)
494
    track[store_name] = onchange => start_tracking(store_name, onchange);
495
#EXPORT track
496

    
497
const untrack = tracking => broadcast.close(tracking.listener);
498
#EXPORT untrack
(4-4/10)