summaryrefslogtreecommitdiff
path: root/src/memidb.ts
blob: 36607d71fa586f86cc15ce0b27d89c28ea428e75 (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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
/*
 This file is part of TALER
 (C) 2017 Inria and GNUnet e.V.

 TALER 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, or (at your option) any later version.

 TALER 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
 TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */

/**
 * In-memory implementation of the IndexedDB interface.
 *
 * Transactions support rollback, but they are all run sequentially within the
 * same MemoryIDBFactory.
 *
 * Every operation involves copying the whole database state, making it only
 * feasible for small databases.
 */

/* work in progres ... */
/* tslint:disable */ 


const structuredClone = require("structured-clone");
const structuredSerialize = require("structured-clone").serialize;


interface StoredObject {
  key: any;
  object: string;
}

interface Store {
  name: string;
  keyPath: string | string[];
  keyGenerator: number;
  autoIncrement: boolean;
  objects: { [strKey: string]: StoredObject };
}


interface Database {
  name: string;
  version: number;
  stores: { [name: string]: Store };
}


interface Databases {
  [name: string]: Database;
}


/**
 * Resolved promise, used to schedule various things
 * by calling .next on it.
 */
const alreadyResolved = Promise.resolve();


class MyDomStringList extends Array<string> implements DOMStringList {
  contains(s: string) {
    for (let i = 0; i < this.length; i++) {
      if (s === this[i]) {
        return true;
      }
    }
    return false;
  }
  item(i: number) {
    return this[i];
  }
}


function callEventHandler(h: EventListenerOrEventListenerObject, evt: Event, target: any) {
  if ("handleEvent" in h) {
    (h as EventListenerObject).handleEvent(evt);
  } else {
    (h as EventListener).call(target, evt);
  }
}

class MyRequest implements IDBRequest {
  onerror: (this: IDBRequest, ev: Event) => any;

  onsuccess: (this: IDBRequest, ev: Event) => any;
  successHandlers: Array<(this: IDBRequest, ev: Event) => any>;

  done: boolean = false;

  constructor(public _transaction: Transaction, public runner: () => void) {
  }

  callSuccess(ev: Event) {
    if (this.onsuccess) {
      this.onsuccess(ev);
    }
    for (let h of this.successHandlers) {
      h.call(this, ev);
    }
  }

  get error(): DOMException {
    return (null as any) as DOMException;
  }

  get result(): any {
    return null;
  }

  get source() {
    // buggy type definitions don't allow null even though it's in
    // the spec.
    return (null as any) as (IDBObjectStore | IDBIndex | IDBCursor);
  }

  get transaction() {
    return this._transaction;
  }

  dispatchEvent(evt: Event): boolean {
    return false;
  }

  get readyState() {
    if (this.done) {
      return "done";
    }
    return "pending";
  }

  removeEventListener(type: string,
                      listener?: EventListenerOrEventListenerObject,
                      options?: boolean | EventListenerOptions): void {
    throw Error("not implemented");
  }

  addEventListener(type: string,
                   listener: EventListenerOrEventListenerObject,
                   useCapture?: boolean): void {
    switch (type) {
      case "success":
        this.successHandlers.push(listener as any);
        break;
    }
  }
}

class OpenDBRequest extends MyRequest implements IDBOpenDBRequest {
  onblocked: (this: IDBOpenDBRequest, ev: Event) => any;

  onupgradeneeded: (this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any;
  upgradeneededHandlers: Array<(this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any> = [];

  callOnupgradeneeded(ev: IDBVersionChangeEvent) {
    if (this.onupgradeneeded) {
      this.onupgradeneeded(ev);
    }
    for (let h of this.upgradeneededHandlers) {
      h.call(this, ev);
    }
  }

  removeEventListener(type: string,
                      listener?: EventListenerOrEventListenerObject,
                      options?: boolean | EventListenerOptions): void {
    throw Error("not implemented");
  }

  addEventListener(type: string,
                   listener: EventListenerOrEventListenerObject,
                   useCapture?: boolean): void {
    switch (type) {
      case "upgradeneeded":
        this.upgradeneededHandlers.push(listener as any);
        break;
      default:
        super.addEventListener(type, listener, useCapture);
    }
  }
}


class MyObjectStore implements IDBObjectStore  {
  get indexNames() {
    return new DOMStringList();
  }

  constructor(public transaction: Transaction, public dbName: string, public storeName: string) {
  }

  get keyPath() {
    return this.transaction.db.dbData.stores[this.storeName].keyPath;
  }

  get name() {
    return this.storeName;
  }

  get autoIncrement() {
    return this.transaction.db.dbData.stores[this.storeName].autoIncrement;
  }

  add(value: any, key?: any): IDBRequest {
    throw Error("not implemented");
  }

  put(value: any, key?: any): IDBRequest {
    throw Error("not implemented");
  }

  delete(key: any): IDBRequest {
    throw Error("not implemented");
  }

  get(key: any): IDBRequest {
    throw Error("not implemented");
  }

  deleteIndex(indexName: string) {
    throw Error("not implemented");
  }

  clear(): IDBRequest {
    throw Error("not implemented");
  }

  count(key?: any): IDBRequest {
    throw Error("not implemented");
  }

  createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex {
    throw Error("not implemented");
  }

  index(indexName: string): IDBIndex {
    throw Error("not implemented");
  }

  openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest {
    throw Error("not implemented");
  }
}


class Db implements IDBDatabase {
  
  onabort: (this: IDBDatabase, ev: Event) => any;
  onerror: (this: IDBDatabase, ev: Event) => any;
  onversionchange: (ev: IDBVersionChangeEvent) => any;

  constructor(private _name: string, private _version: number, private factory: MemoryIDBFactory) {
  }

  get dbData() {
    return this.factory.data[this._name];
  }

  get name() {
    return this._name;
  }

  get objectStoreNames() {
    return new MyDomStringList();
  }

  get version() {
    return this._version;
  }

  close() {
  }

  createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore {
    let tx = this.factory.getTransaction();
    if (tx.mode !== "versionchange") {
      throw Error("invalid mode");
    }
    throw Error("not implemented");
  }

  deleteObjectStore(name: string): void {
    throw Error("not implemented");
  }

  transaction(storeNames: string | string[], mode: IDBTransactionMode = "readonly"): IDBTransaction {
    const tx = new Transaction(this._name, this, mode);
    return tx;
  }

  dispatchEvent(evt: Event): boolean {
    throw Error("not implemented");
  }

  removeEventListener(type: string,
                      listener?: EventListenerOrEventListenerObject,
                      options?: boolean | EventListenerOptions): void {
    throw Error("not implemented");
  }

  addEventListener(type: string,
                   listener: EventListenerOrEventListenerObject,
                   useCapture?: boolean): void {
    throw Error("not implemented");
  }
}

enum TransactionState {
  Created = 1,
  Running = 2,
  Commited = 3,
  Aborted = 4,
}

class Transaction implements IDBTransaction {
  readonly READ_ONLY: string = "readonly";
  readonly READ_WRITE: string = "readwrite";
  readonly VERSION_CHANGE: string = "versionchange";

  onabort: (this: IDBTransaction, ev: Event) => any;
  onerror: (this: IDBTransaction, ev: Event) => any;
  oncomplete: (this: IDBTransaction, ev: Event) => any;

  completeHandlers: Array<(this: IDBTransaction, ev: Event) => any> = [];

  state: TransactionState = TransactionState.Created;

  _transactionDbData: Database|undefined;

  constructor(public dbName: string, public dbHandle: Db, public _mode: IDBTransactionMode) {
  }

  get mode() {
    return this._mode;
  }

  start() {
    if (this.state != TransactionState.Created) {
      throw Error();
    }
    this._transactionDbData = structuredClone(this.dbHandle.dbData);
  }

  get error(): DOMException {
    throw Error("not implemented");
  }

  get db() {
    return this.dbHandle;
  }

  get transactionDbData() {
    if (this.state != TransactionState.Running) {
      throw Error();
    }
    let d = this._transactionDbData;
    if (!d) {
      throw Error();
    }
    return d;
  }

  abort() {
    throw Error("not implemented");
  }

  objectStore(storeName: string): IDBObjectStore {
    return new MyObjectStore(this, this.dbName, storeName);
  }

  dispatchEvent(evt: Event): boolean {
    throw Error("not implemented");
  }

  removeEventListener(type: string,
                      listener?: EventListenerOrEventListenerObject,
                      options?: boolean | EventListenerOptions): void {
    throw Error("not implemented");
  }

  addEventListener(type: string,
                   listener: EventListenerOrEventListenerObject,
                   useCapture?: boolean): void {
    switch (type) {
      case "complete":
        this.completeHandlers.push(listener as any);
      break;
    }
  }

  callComplete(ev: Event) {
    if (this.oncomplete) {
      this.oncomplete(ev);
    }
    for (let h of this.completeHandlers) {
      h.call(this, ev);
    }
  }
}


/**
 * Polyfill for CustomEvent.
 */
class MyEvent implements Event {
  readonly NONE: number = 0;
  readonly CAPTURING_PHASE: number = 1;
  readonly AT_TARGET: number = 2;
  readonly BUBBLING_PHASE: number = 3;

  _bubbles = false;
  _cancelable = false;
  _target: any;
  _currentTarget: any;
  _defaultPrevented: boolean = false;
  _eventPhase: number = 0;
  _timeStamp: number = 0;
  _type: string;

  constructor(typeArg: string) {
    this._type = typeArg;
  }

  get eventPhase() {
    return this._eventPhase;
  }

  get returnValue() {
    return this.defaultPrevented;
  }

  set returnValue(v: boolean) {
    if (v) {
      this.preventDefault();
    }
  }

  get isTrusted() {
    return false;
  }

  get bubbles() {
    return this._bubbles;
  }

  get cancelable() {
    return this._cancelable;
  }

  set cancelBubble(v: boolean) {
    if (v) {
      this.stopPropagation();
    }
  }

  get defaultPrevented() {
    return this._defaultPrevented;
  }

  stopPropagation() {
    throw Error("not implemented");
  }

  get currentTarget() {
    return this._currentTarget;
  }

  get target() {
    return this._target;
  }

  preventDefault() {
  }

  get srcElement() {
    return this.target;
  }

  get timeStamp() {
    return this._timeStamp;
  }

  get type() {
    return this._type;
  }

  get scoped() {
    return false;
  }

  initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean) {
    if (this._eventPhase != 0) {
      return;
    }

    this._type = eventTypeArg;
    this._bubbles = canBubbleArg;
    this._cancelable = cancelableArg;
  }

  stopImmediatePropagation() {
    throw Error("not implemented");
  }

  deepPath(): EventTarget[] {
    return [];
  }
}


class VersionChangeEvent extends MyEvent {
  _newVersion: number|null;
  _oldVersion: number;
  constructor(oldVersion: number, newVersion?: number) {
    super("VersionChange");
    this._oldVersion = oldVersion;
    this._newVersion = newVersion || null;
  }

  get newVersion() {
    return this._newVersion;
  }

  get oldVersion() {
    return this._oldVersion;
  }
}


class MemoryIDBFactory implements IDBFactory {
  data: Databases = {};

  currentRequest: MyRequest|undefined;

  scheduledRequests: MyRequest[] = [];

  private addRequest(r: MyRequest) {
    this.scheduledRequests.push(r);
    if (this.currentRequest) {
      return;
    }
    const runNext = (prevRequest?: MyRequest) => {
      const nextRequest = this.scheduledRequests.shift();
      if (nextRequest) {
        const tx = nextRequest.transaction;

        if (tx.state === TransactionState.Running) {
          // Okay, we're continuing with the same transaction
        } else if (tx.state === TransactionState.Created) {
          tx.start();
        } else {
          throw Error();
        }

        this.currentRequest = nextRequest;
        this.currentRequest.runner();
        this.currentRequest.done = true;
        this.currentRequest = undefined;
        runNext(nextRequest);
      } else if (prevRequest) {
        // We have no other request scheduled, so
        // auto-commit the transaction that the
        // previous request worked on.
        let lastTx = prevRequest._transaction;
        this.data[lastTx.dbName] = lastTx.transactionDbData;
      }
    };
    alreadyResolved.then(() => {
      runNext();
    });
  }

  /**
   * Get the only transaction that is active right now
   * or throw if no transaction is active.
   */
  getTransaction() {
    const req = this.currentRequest;
    if (!req) {
      throw Error();
    }
    return req.transaction;
  }

  cmp(a: any, b: any): number {
    throw Error("not implemented");
  }

  deleteDatabase(name: string): IDBOpenDBRequest {
    throw Error("not implemented");
  }

  open(dbName: string, version?: number): IDBOpenDBRequest {
    if (version !== undefined && version <= 0) {
      throw Error("invalid version");
    }

    let upgradeNeeded = false;
    let mydb: Database;
    if (dbName in this.data) {
      mydb = this.data[dbName];
      if (version === undefined || version == mydb.version) {
        // we can open without upgrading
      } else if (version > mydb.version) {
        upgradeNeeded = true;
      } else {
        throw Error("version error");
      }
    } else {
      mydb = {
        name: dbName,
        stores: {},
        version: (version || 1),
      };
      upgradeNeeded = true;
    }

    const db = new Db(dbName, mydb.version, this);
    const tx = new Transaction(dbName, db, "versionchange");

    const req = new OpenDBRequest(tx, () => {
      if (upgradeNeeded) {
        let versionChangeEvt = new VersionChangeEvent(mydb.version, version);
        req.callOnupgradeneeded(versionChangeEvt);
      }
      let successEvent = new MyEvent("success");
      req.callSuccess(successEvent);
    });

    this.addRequest(req);

    return req;
  }
}