-
Notifications
You must be signed in to change notification settings - Fork 6
/
IDBTransaction-impl.js
699 lines (673 loc) · 34.2 KB
/
IDBTransaction-impl.js
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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
const assert = require('assert')
const compare = require('./compare')
const rescue = require('rescue')
const { Future } = require('perhaps')
const { dispatchEvent } = require('./dispatch')
const Verbatim = require('verbatim')
const { vivify } = require('./setter')
const { valuify, MAX } = require('./value')
const { Queue } = require('avenue')
const { setupForSimpleEventAccessors } = require('./living/helpers/create-event-accessor')
const EventTarget = require('./living/generated/EventTarget')
const Event = require('./living/generated/Event')
const IDBRequest = require('./living/generated/IDBRequest')
const IDBOpenDBRequest = require('./living/generated/IDBOpenDBRequest')
const IDBVersionChangeEvent = require('./living/generated/IDBVersionChangeEvent')
const IDBObjectStore = require('./living/generated/IDBObjectStore')
const DOMStringList = require('./living/generated/DOMStringList')
const DOMException = require('domexception/lib/DOMException')
const EventTargetImpl = require('./living/idl/EventTarget-impl').implementation
const webidl = require('./living/generated/utils')
const structuredClone = require('./structuredClone')
class IDBTransactionImpl extends EventTargetImpl {
constructor (globalObject, args, { schema, request = null, database, mode, names = [], previousVersion = null, durability }) {
super(globalObject, [], {})
if (mode == null) {
throw new Error
}
this.durability = durability
this._globalObject = globalObject
this._schema = schema
this._state = 'active'
this._database = database
this._request = request
this._queue = []
this._mode = mode
this._names = names
this._previousVersion = previousVersion
}
get objectStoreNames () {
const array = this._names.length == 0 ? this._schema.getObjectStoreNames().sort() : this._names.sort()
return DOMStringList.create(this._globalObject, [], { array })
}
get mode () {
return this._mode
}
get db () {
return this._database
}
_getTheParent() {
return this._database
}
objectStore (name) {
if (this._state == 'finished') {
throw DOMException.create(this._globalObject, [ 'TODO: message', 'InvalidStateError' ], {})
}
if (
this._names.length == 0
? this._schema.getObjectStore(name) == null
: !~this._names.indexOf(name)
) {
throw DOMException.create(this._globalObject, [ 'TODO: message', 'NotFoundError' ], {})
}
return IDBObjectStore.create(this._globalObject, [], { transaction: this, schema: this._schema, name })
}
// **TODO** What happens in a double abort?
abort () {
this._state = 'finished'
this._schema.abort()
if (this._mode == 'versionchange') {
this._database.version = this._previousVersion
}
this._aborted = true
}
async _next ({ store, request, cursor }, transaction) {
let unique = null
FOREVER: for (;;) {
const next = cursor._inner.next()
if (next.done) {
cursor._outer.next = await cursor._outer.iterator.next()
if (cursor._outer.next.done) {
if (unique != null) {
const got = { key: unique.key, value: await transaction.get(store.qualified, [ unique.referent ]) }
unique = null
return got
}
return null
} else {
cursor._inner = cursor._outer.next.value[Symbol.iterator]()
}
} else {
switch (cursor._type) {
case 'store': {
return { key: next.value.key, value: next.value }
}
case 'index': {
if (cursor._direction == 'prevunique') {
if (unique != null) {
if (compare(this._globalObject, unique.key, next.value.key) != 0) {
return { key: unique.key, value: await transaction.get(store.qualified, [ unique.referent ]) }
}
}
unique = next.value
} else if (cursor._direction == 'nextunique') {
if (
cursor._key != null &&
compare(this._globalObject, cursor._key, next.value.key) == 0
) {
continue
}
return { key: next.value.key, value: await transaction.get(store.qualified, [ next.value.referent ]) }
} else {
return { key: next.value.key, value: await transaction.get(store.qualified, [ next.value.referent ]) }
}
}
}
}
}
}
_delete (transaction, store, { key, value }) {
transaction.unset(store.qualified, [ key ])
for (const indexName in store.index) {
if (! store.index.hasOwnProperty(indexName)) {
continue
}
const index = this._schema._pending.store[store.index[indexName]]
if (! index.extant) {
continue
}
let extracted
try {
extracted = valuify(this._globalObject, this._schema.getExtractor(index.id)(value))
} catch (error) {
// **TODO** Why doesn't `{ name: 'DataError' }` work. Step through
// it with `test/idbobjectstore_add14.wpt.t.js`.
rescue(error, [ this._globalObject.DOMException ])
continue
}
transaction.unset(index.qualified, [ extracted, key ])
}
}
_extractIndexed (index, value) {
const values = []
const extracted = this._schema.getExtractor(index.id)(value)
if (index.multiEntry && Array.isArray(extracted)) {
for (const value of extracted) {
try {
values.push(valuify(this._globalObject, value))
} catch (error) {
// **TODO** Why doesn't `{ name: 'DataError' }` work. Step through
// it with `test/idbobjectstore_add14.wpt.t.js`.
rescue(error, [ this._globalObject.DOMException ])
}
}
} else {
try {
values.push(valuify(this._globalObject, extracted))
} catch (error) {
// **TODO** Why doesn't `{ name: 'DataError' }` work. Step through
// it with `test/idbobjectstore_add14.wpt.t.js`.
rescue(error, [ this._globalObject.DOMException ])
}
}
return values
}
_dispatchItem ({ cursor, request }, got) {
request.readyState = 'done'
if (got == null) {
request._result = null
} else {
cursor._key = got.key
cursor._value = got.value
cursor._gotValue = true
}
return dispatchEvent(this, request, Event.createImpl(this._globalObject, [ 'success' ], {}))
}
// Most of the logic of this implementation is in this one function.
// The interface implementations do a lot of argument validation, but
// most of the real work is here.
//
async _run (transaction) {
await new Promise(resolve => setImmediate(resolve))
while (this._queue.length != 0) {
const event = this._queue.shift()
if (this._state == 'finished') {
const { request } = event
if (request != null) {
delete request._result
request.readyState = 'done'
request._error = DOMException.create(this._globalObject, [ 'TODO: message', 'AbortError' ], {})
await dispatchEvent(null, request, Event.createImpl(this._globalObject, [ 'error', { bubbles: true, cancelable: true } ], {}))
}
continue
}
SWITCH: switch (event.method) {
// Don't worry about rollback of the update to the schema object. We
// are not going to use this object if the upgrade fails.
case 'create': {
switch (event.type) {
case 'store': {
const { store } = event
transaction.set('schema', store)
await transaction.store(store.qualified, { key: 'indexeddb' })
}
break
case 'index': {
const { store, index } = event
await transaction.store(index.qualified, { key: 'indexeddb', referent: 'indexeddb' })
transaction.set('schema', store)
transaction.set('schema', index)
const extractor = this._schema.getExtractor(index.id)
for await (const items of transaction.cursor(store.qualified)) {
for (const item of items) {
for (const value of this._extractIndexed(index, item.value)) {
transaction.set(index.qualified, { key: value, referent: item.key })
}
}
}
if (index.unique) {
let previous = null, count = 0
OUTER: for await (const items of transaction.cursor(index.qualified)) {
for (const item of items) {
if (count++ == 0) {
previous = item
continue
}
if (compare(this._globalObject, previous.key, item.key) == 0) {
this.error = DOMException.create(this._globalObject, [ 'TODO: message', 'ConstraintError' ], {})
this.abort()
break OUTER
}
previous = item
}
}
}
index.extant = true
}
break
}
}
break
case 'deleteStore': {
const { id } = event
}
break
case 'index': {
}
break
case 'set': {
const { store, key, value, overwrite, request } = event
const got = await transaction.get(store.qualified, [ key ])
if (got != null) {
if (! overwrite) {
const event = Event.createImpl(this._globalObject, [ 'error', { bubbles: true, cancelable: true } ], {})
const error = DOMException.create(this._globalObject, [ 'Unique key constraint violation.', 'ConstraintError' ], {})
request.readyState = 'done'
request._error = error
const caught = await dispatchEvent(null, request, event)
if (!event._canceledFlag) {
this.abort()
}
console.log('???', caught)
break SWITCH
}
for (const indexName in store.index) {
if (! store.index.hasOwnProperty(indexName)) {
continue
}
const index = this._schema._pending.store[store.index[indexName]]
if (! index.extant) {
continue
}
const values = this._extractIndexed(index, got.value)
for (const value of values) {
transaction.unset(index.qualified, [ value, key ])
}
}
}
request._result = key
const record = { key, value }
for (const indexName in store.index) {
// Necessary to pass web platform tests. Some Web Platform Tests
// monkey patch Object in order to assert that clone and injection
// assignments are done through property definitions, not setters.
if (! store.index.hasOwnProperty(indexName)) {
continue
}
const index = this._schema._pending.store[store.index[indexName]]
if (! index.extant) {
continue
}
const values = this._extractIndexed(index, record.value)
for (const value of values) {
if (index.unique) {
const got = await transaction.cursor(index.qualified, [ value ])
.terminate(item => compare(this._globalObject, item.key, value) != 0)
.array()
if (got.length != 0) {
const event = Event.createImpl(this._globalObject, [ 'error', { bubbles: true, cancelable: true } ], {})
const error = DOMException.create(this._globalObject, [ 'Unique key constraint violation.', 'ConstraintError' ], {})
request.readyState = 'done'
request._error = error
await dispatchEvent(this, request, event)
if (!event._canceledFlag) {
this.error = DOMException.create(this._globalObject, [ 'TODO: message', 'ConstraintError' ], {})
this.abort()
}
break SWITCH
}
}
transaction.set(index.qualified, { key: value, referent: key })
}
}
transaction.set(store.qualified, record)
request.readyState = 'done'
await dispatchEvent(this, request, Event.createImpl(this._globalObject, [ 'success', { bubbles: false, cancelable: false }], {}))
}
break
case 'get': {
switch (event.type) {
case 'store': {
const { store, query, request, keys } = event
const got = await transaction.cursor(store.qualified, query.lower ? [ query.lower ] : null)
.terminate(item => ! query.includes(item.key))
.limit(1)
.array()
if (got.length != 0) {
request._result = structuredClone(this._globalObject, keys ? got[0].key : got[0].value)
}
request.readyState = 'done'
await dispatchEvent(this, request, Event.createImpl(this._globalObject, [ 'success' ], {}))
}
break
case 'index': {
const { store, query, index, key, request } = event
// TODO What if query lower is `null` but query upper is not?
const cursor = query.lower == null
? transaction.cursor(index.qualified)
: transaction.cursor(index.qualified, [ query.lower ])
const indexGot = await cursor.terminate(item => ! query.includes(item.key)).limit(1).array()
if (indexGot.length != 0) {
const got = await transaction.get(store.qualified, [ indexGot[0].referent ])
request._result = Verbatim.deserialize(Verbatim.serialize(key ? got.key : got.value))
}
request.readyState = 'done'
await dispatchEvent(this, request, Event.createImpl(this._globalObject, [ 'success' ], {}))
}
break
}
}
break
case 'getAll': {
switch (event.type) {
case 'store': {
const { store, query, count, request, keys } = event
const cursor = transaction.cursor(store.qualified, query.lower == null ? null : [ query.lower ])
const terminated = query.lower == null ? cursor : cursor.terminate(item => ! query.includes(item.key))
const limited = count == null || count == 0 ? terminated : cursor.limit(count)
const exclusive = query.lower != null && query.lowerOpen ? limited.exclusive() : limited
const array = await exclusive.array()
if (keys) {
request._result = array.map(item => item.key)
} else {
request._result = array.map(item => item.value)
}
request.readyState = 'done'
await dispatchEvent(this, request, Event.createImpl(this._globalObject, [ 'success' ], {}))
}
break
case 'index': {
const { store, index, query, count, request, keys } = event
// Here we can't just the `exclusive` property becasue we are always
// going to be searching by a partial key. We use our special `MAX`
// when we want an exclusive search so that we will be at the record
// greater than the greatest possible record of the specified key.
// Exclusive flag is not necessary since this record will never be
// found.
const key = query.lower == null ? null : [ query.lower ]
const cursor = transaction.cursor(index.qualified, key)
const terminated = query.lower == null ? cursor : cursor.terminate(item => ! query.includes(item.key))
const limited = count == null || count == 0 ? terminated : cursor.limit(count)
const exclusive = query.lowerOpen ? limited.exclusive() : limited
// TODO Use Memento join.
// TODO Do a structured copy.
request._result = []
for await (const items of exclusive) {
for (const item of items) {
const got = await transaction.get(store.qualified, [ item.referent ])
request._result.push(keys ? got.key : got.value)
}
}
request.readyState = 'done'
await dispatchEvent(this, request, Event.createImpl(this._globalObject, [ 'success' ], {}))
}
break
}
}
break
case 'openCursor': {
const { query, store, index, request, cursor, direction } = event
let builder
switch (event.type) {
case 'store': {
switch (direction) {
case 'next':
case 'nextunique': {
builder = query.lower == null
? transaction.cursor(store.qualified)
: transaction.cursor(store.qualified, [ query.lower ])
if (query.lowerOpen) {
builder = builder.exclusive()
}
if (query.upper != null) {
builder = builder.terminate(item => ! query.includes(item.key))
}
}
break
case 'prev':
case 'prevunique': {
builder = query.upper == null
? transaction.cursor(store.qualified)
: transaction.cursor(store.qualified, [ query.upper ])
if (query.lower != null) {
builder = builder.terminate(item => ! query.includes(item.key))
}
builder = builder.reverse()
}
break
}
}
break
case 'index': {
switch (direction) {
case 'next':
case 'nextunique': {
// Here we can't just the `exclusive` property becasue we are always
// going to be searching by a partial key. We use our special `MAX`
// when we want an exclusive search so that we will be at the record
// greater than the greatest possible record of the specified key.
// Exclusive flag is not necessary since this record will never be
// found.
const key = query.lower == null ? null : [ query.lower ]
builder = transaction.cursor(index.qualified, key)
if (query.lowerOpen) {
builder = builder.exclusive()
}
if (query.upper != null) {
builder = builder.terminate(item => ! query.includes(item.key))
}
}
break
case 'prev':
case 'prevunique': {
builder = transaction.cursor(index.qualified, query.upper == null ? null : [ query.upper ])
builder = query.upperOpen ? builder.exclusive() : builder
builder = builder.reverse()
if (query.lower != null) {
builder = builder.terminate(item => ! query.includes(item.key))
}
}
break
}
}
break
}
cursor._outer = { iterator: builder[Symbol.asyncIterator](), next: null }
cursor._inner = {
next() {
return { done: true, value: null }
}
}
const got = await this._next(event, transaction)
await this._dispatchItem(event, got)
}
break
case 'continue': {
const { store, request, cursor, key, primaryKey } = event
if (primaryKey == null) {
if (cursor._direction == 'prevunique' && cursor._type == 'index') {
let builder
const query = cursor._query, index = cursor._index
builder = transaction.cursor(index.qualified, [ cursor._key ])
builder = builder.reverse()
builder = builder.exclusive()
if (query.lower != null) {
builder = builder.terminate(item => ! query.includes(item.key))
}
cursor._outer = { iterator: builder[Symbol.asyncIterator](), next: null }
cursor._inner = {
next() {
return { done: true, value: null }
}
}
}
for (;;) {
const got = await this._next(event, transaction)
if (
got == null ||
key == null ||
compare(this._globalObject, key, got.key) <= 0
) {
await this._dispatchItem(event, got)
break
}
}
} else {
for (;;) {
const got = await this._next(event, transaction)
if (
got == null
||
(
compare(this._globalObject, got.key, key) == 0 &&
compare(this._globalObject, got.value.key, primaryKey) >= 0
)
||
compare(this._globalObject, got.key, key) > 0
) {
await this._dispatchItem(event, got)
break
}
}
}
}
break
case 'advance': {
const { store, request, cursor } = event
if (cursor._direction == 'prevunique') {
throw new Error
}
let count = event.count - 1
// TODO Tighten loop.
while (count != 0) {
const next = cursor._inner.next()
if (next.done) {
cursor._outer.next = await cursor._outer.iterator.next()
if (cursor._outer.next.done) {
request._result = null
request.readyState = 'done'
await dispatchEvent(this, request, Event.createImpl(this._globalObject, [ 'success' ], {}))
break SWITCH
}
}
count--
}
const got = await this._next(event, transaction)
await this._dispatchItem(event, got)
}
break
case 'count': {
switch (event.type) {
case 'store': {
const { store, request, query } = event
request._result = 0
let cursor = query.lower == null ? transaction.cursor(store.qualified) : transaction.cursor(store.qualified, [ query.lower ])
cursor = query.upper == null ? cursor : cursor.terminate(item => ! query.includes(item.key))
for await (const items of cursor) {
for (const item of items) {
request._result++
}
}
request.readyState = 'done'
await dispatchEvent(this, request, Event.createImpl(this._globalObject, [ 'success' ], {}))
}
break
case 'index': {
const { index, store, request, query } = event
request._result = 0
let cursor = query.lower == null ? transaction.cursor(index.qualified) : transaction.cursor(index.qualified, [ query.lower ])
cursor = query.upper == null ? cursor : cursor.terminate(item => ! query.includes(item.key))
for await (const items of cursor) {
for (const item of items) {
request._result++
}
}
request.readyState = 'done'
await dispatchEvent(this, request, Event.createImpl(this._globalObject, [ 'success' ], {}))
}
break
}
}
break
case 'clear': {
const { store, request } = event
// TODO Really do not need iterator do I?
for await (const items of transaction.cursor(store.qualified)) {
for (const item of items) {
this._delete(transaction, store, item)
}
}
// TODO Clear an index.
request.readyState = 'done'
await dispatchEvent(this, request, Event.createImpl(this._globalObject, [ 'success' ], {}))
}
break
case 'delete': {
const { store, request, query } = event
let cursor = query.lower == null ? transaction.cursor(store.qualified) : transaction.cursor(store.qualified, [ query.lower ])
cursor = query.upper == null ? cursor : cursor.terminate(item => ! query.includes(item.key))
for await (const items of cursor) {
for (const item of items) {
this._delete(transaction, store, item)
}
}
request.readyState = 'done'
await dispatchEvent(this, request, Event.createImpl(this._globalObject, [ 'success' ], {}))
}
break
case 'rename': {
switch (event.type) {
case 'store': {
const { store } = event
transaction.set('schema', store)
}
break
case 'index': {
const { store, index } = event
transaction.set('schema', store)
transaction.set('schema', index)
}
break
}
}
break
case 'destroy': {
switch (event.type) {
case 'store': {
const { store } = event
// **TODO** remove all associated indexes
await transaction.remove(store.qualified)
}
break
case 'index': {
// **TODO** Remove index from... No, let's just use a
// relation between the index and the store.
const { index } = event
await transaction.remove(index.qualified)
}
break
}
}
break
}
await new Promise(resolve => setImmediate(resolve))
}
if (this._state == 'finished') {
this._schema.reset()
// **TODO** I unset this here and in IDBFactory, so spaghetti.
this._database._transaction = null
await dispatchEvent(null, this, Event.createImpl(this._globalObject, [ 'abort', { bubbles: true, cancelable: true } ], {}))
// Must do this immediately before transaction rollback.
if (this._request) {
this._request.transaction = null
}
if (transaction.rollback) {
transaction.rollback()
}
} else {
this._state = 'committing'
if (transaction.commit) {
await transaction.commit()
}
this._schema.merge()
this._state = 'finished'
this._database._transaction = null
await dispatchEvent(null, this, Event.createImpl(this._globalObject, [ 'complete' ], {}))
if (this._request) {
this._request.transaction = null
}
}
}
}
setupForSimpleEventAccessors(IDBTransactionImpl.prototype, [ 'complete', 'abort', 'error' ]);
module.exports = { implementation: IDBTransactionImpl }