@ohos-ports/lmdb 2.8.6-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +580 -0
  3. package/SECURITY.md +12 -0
  4. package/bin/download-prebuilds.js +15 -0
  5. package/binding.gyp +113 -0
  6. package/build/Release/lmdb.node +0 -0
  7. package/caching.js +212 -0
  8. package/dependencies/lmdb/libraries/liblmdb/COPYRIGHT +20 -0
  9. package/dependencies/lmdb/libraries/liblmdb/Doxyfile +1631 -0
  10. package/dependencies/lmdb/libraries/liblmdb/LICENSE +47 -0
  11. package/dependencies/lmdb/libraries/liblmdb/Makefile +136 -0
  12. package/dependencies/lmdb/libraries/liblmdb/chacha8.c +183 -0
  13. package/dependencies/lmdb/libraries/liblmdb/chacha8.h +14 -0
  14. package/dependencies/lmdb/libraries/liblmdb/crypto.c +121 -0
  15. package/dependencies/lmdb/libraries/liblmdb/intro.doc +192 -0
  16. package/dependencies/lmdb/libraries/liblmdb/lmdb.h +1817 -0
  17. package/dependencies/lmdb/libraries/liblmdb/mdb.c +12555 -0
  18. package/dependencies/lmdb/libraries/liblmdb/mdb_copy.1 +74 -0
  19. package/dependencies/lmdb/libraries/liblmdb/mdb_copy.c +106 -0
  20. package/dependencies/lmdb/libraries/liblmdb/mdb_drop.1 +53 -0
  21. package/dependencies/lmdb/libraries/liblmdb/mdb_drop.c +154 -0
  22. package/dependencies/lmdb/libraries/liblmdb/mdb_dump.1 +94 -0
  23. package/dependencies/lmdb/libraries/liblmdb/mdb_dump.c +333 -0
  24. package/dependencies/lmdb/libraries/liblmdb/mdb_load.1 +97 -0
  25. package/dependencies/lmdb/libraries/liblmdb/mdb_load.c +530 -0
  26. package/dependencies/lmdb/libraries/liblmdb/mdb_stat.1 +83 -0
  27. package/dependencies/lmdb/libraries/liblmdb/mdb_stat.c +276 -0
  28. package/dependencies/lmdb/libraries/liblmdb/midl-sparse.c +452 -0
  29. package/dependencies/lmdb/libraries/liblmdb/midl.c +452 -0
  30. package/dependencies/lmdb/libraries/liblmdb/midl.h +208 -0
  31. package/dependencies/lmdb/libraries/liblmdb/module.c +101 -0
  32. package/dependencies/lmdb/libraries/liblmdb/module.h +16 -0
  33. package/dependencies/lmdb/libraries/liblmdb/mtest.c +178 -0
  34. package/dependencies/lmdb/libraries/liblmdb/mtest2.c +124 -0
  35. package/dependencies/lmdb/libraries/liblmdb/mtest3.c +133 -0
  36. package/dependencies/lmdb/libraries/liblmdb/mtest4.c +168 -0
  37. package/dependencies/lmdb/libraries/liblmdb/mtest5.c +135 -0
  38. package/dependencies/lmdb/libraries/liblmdb/mtest6.c +141 -0
  39. package/dependencies/lmdb/libraries/liblmdb/mtest_enc.c +190 -0
  40. package/dependencies/lmdb/libraries/liblmdb/mtest_enc2.c +189 -0
  41. package/dependencies/lmdb/libraries/liblmdb/mtest_remap.c +177 -0
  42. package/dependencies/lmdb/libraries/liblmdb/sample-bdb.txt +73 -0
  43. package/dependencies/lmdb/libraries/liblmdb/sample-mdb.txt +62 -0
  44. package/dependencies/lmdb/libraries/liblmdb/tooltag +27 -0
  45. package/dependencies/lmdb-data-v1/libraries/liblmdb/CHANGES +266 -0
  46. package/dependencies/lmdb-data-v1/libraries/liblmdb/COPYRIGHT +20 -0
  47. package/dependencies/lmdb-data-v1/libraries/liblmdb/Doxyfile +1631 -0
  48. package/dependencies/lmdb-data-v1/libraries/liblmdb/LICENSE +47 -0
  49. package/dependencies/lmdb-data-v1/libraries/liblmdb/intro.doc +192 -0
  50. package/dependencies/lmdb-data-v1/libraries/liblmdb/lmdb.h +1608 -0
  51. package/dependencies/lmdb-data-v1/libraries/liblmdb/mdb.c +10320 -0
  52. package/dependencies/lmdb-data-v1/libraries/liblmdb/mdb_copy.1 +55 -0
  53. package/dependencies/lmdb-data-v1/libraries/liblmdb/mdb_copy.c +82 -0
  54. package/dependencies/lmdb-data-v1/libraries/liblmdb/mdb_dump.1 +75 -0
  55. package/dependencies/lmdb-data-v1/libraries/liblmdb/mdb_dump.c +319 -0
  56. package/dependencies/lmdb-data-v1/libraries/liblmdb/mdb_load.1 +84 -0
  57. package/dependencies/lmdb-data-v1/libraries/liblmdb/mdb_load.c +496 -0
  58. package/dependencies/lmdb-data-v1/libraries/liblmdb/mdb_stat.1 +64 -0
  59. package/dependencies/lmdb-data-v1/libraries/liblmdb/mdb_stat.c +263 -0
  60. package/dependencies/lmdb-data-v1/libraries/liblmdb/midl.c +359 -0
  61. package/dependencies/lmdb-data-v1/libraries/liblmdb/midl.h +186 -0
  62. package/dependencies/lmdb-data-v1/libraries/liblmdb/mtest.c +177 -0
  63. package/dependencies/lmdb-data-v1/libraries/liblmdb/mtest2.c +124 -0
  64. package/dependencies/lmdb-data-v1/libraries/liblmdb/mtest3.c +133 -0
  65. package/dependencies/lmdb-data-v1/libraries/liblmdb/mtest4.c +168 -0
  66. package/dependencies/lmdb-data-v1/libraries/liblmdb/mtest5.c +135 -0
  67. package/dependencies/lmdb-data-v1/libraries/liblmdb/mtest6.c +141 -0
  68. package/dependencies/lmdb-data-v1/libraries/liblmdb/sample-bdb.txt +73 -0
  69. package/dependencies/lmdb-data-v1/libraries/liblmdb/sample-mdb.txt +62 -0
  70. package/dependencies/lmdb-data-v1/libraries/liblmdb/tooltag +22 -0
  71. package/dependencies/lz4/LICENSE +11 -0
  72. package/dependencies/lz4/lib/LICENSE +24 -0
  73. package/dependencies/lz4/lib/Makefile +225 -0
  74. package/dependencies/lz4/lib/README.md +169 -0
  75. package/dependencies/lz4/lib/dll/example/Makefile +63 -0
  76. package/dependencies/lz4/lib/dll/example/README.md +69 -0
  77. package/dependencies/lz4/lib/dll/example/fullbench-dll.sln +25 -0
  78. package/dependencies/lz4/lib/dll/example/fullbench-dll.vcxproj +182 -0
  79. package/dependencies/lz4/lib/dll/liblz4.def +62 -0
  80. package/dependencies/lz4/lib/liblz4-dll.rc.in +35 -0
  81. package/dependencies/lz4/lib/liblz4.pc.in +14 -0
  82. package/dependencies/lz4/lib/lz4.c +2722 -0
  83. package/dependencies/lz4/lib/lz4.h +842 -0
  84. package/dependencies/lz4/lib/lz4file.c +311 -0
  85. package/dependencies/lz4/lib/lz4file.h +93 -0
  86. package/dependencies/lz4/lib/lz4frame.c +2078 -0
  87. package/dependencies/lz4/lib/lz4frame.h +692 -0
  88. package/dependencies/lz4/lib/lz4frame_static.h +47 -0
  89. package/dependencies/lz4/lib/lz4hc.c +1631 -0
  90. package/dependencies/lz4/lib/lz4hc.h +413 -0
  91. package/dependencies/lz4/lib/xxhash.c +1030 -0
  92. package/dependencies/lz4/lib/xxhash.h +328 -0
  93. package/dependencies/v8/v8-fast-api-calls-v16.h +791 -0
  94. package/dependencies/v8/v8-fast-api-calls.h +888 -0
  95. package/dict/dict.txt +1 -0
  96. package/dict/dict2.txt +1 -0
  97. package/dist/index.cjs +2950 -0
  98. package/dist/index.cjs.map +1 -0
  99. package/index.d.cts +420 -0
  100. package/index.d.ts +450 -0
  101. package/index.js +38 -0
  102. package/keys.js +116 -0
  103. package/level.js +27 -0
  104. package/native.js +85 -0
  105. package/node-index.js +32 -0
  106. package/open.js +448 -0
  107. package/package.json +124 -0
  108. package/read.js +833 -0
  109. package/rollup.config.js +12 -0
  110. package/src/compression.cpp +225 -0
  111. package/src/cursor.cpp +395 -0
  112. package/src/dbi.cpp +382 -0
  113. package/src/env.cpp +1030 -0
  114. package/src/lmdb-js.cpp +64 -0
  115. package/src/lmdb-js.h +633 -0
  116. package/src/misc.cpp +593 -0
  117. package/src/ordered-binary.cpp +46 -0
  118. package/src/txn.cpp +210 -0
  119. package/src/v8-functions.cpp +170 -0
  120. package/src/windows.c +35 -0
  121. package/src/writer.cpp +537 -0
  122. package/util/RangeIterable.js +236 -0
  123. package/util/set-optional-deps.cjs +14 -0
  124. package/util/when.js +8 -0
  125. package/write.js +912 -0
package/write.js ADDED
@@ -0,0 +1,912 @@
1
+ import { getAddress, getBufferAddress, write, compress, lmdbError } from './native.js';
2
+ import { when } from './util/when.js';
3
+ var backpressureArray;
4
+
5
+ const WAITING_OPERATION = 0x2000000;
6
+ const BACKPRESSURE_THRESHOLD = 300000;
7
+ const TXN_DELIMITER = 0x8000000;
8
+ const TXN_COMMITTED = 0x10000000;
9
+ const TXN_FLUSHED = 0x20000000;
10
+ const TXN_FAILED = 0x40000000;
11
+ export const FAILED_CONDITION = 0x4000000;
12
+ const REUSE_BUFFER_MODE = 512;
13
+ const RESET_BUFFER_MODE = 1024;
14
+ const NO_RESOLVE = 16;
15
+ const HAS_TXN = 8;
16
+ const CONDITIONAL_VERSION_LESS_THAN = 0x800;
17
+ const CONDITIONAL_ALLOW_NOTFOUND = 0x800;
18
+
19
+ const SYNC_PROMISE_SUCCESS = Promise.resolve(true);
20
+ const SYNC_PROMISE_FAIL = Promise.resolve(false);
21
+ SYNC_PROMISE_SUCCESS.isSync = true;
22
+ SYNC_PROMISE_FAIL.isSync = true;
23
+ const PROMISE_SUCCESS = Promise.resolve(true);
24
+ export const ABORT = 4.452694326329068e-106; // random/unguessable numbers, which work across module/versions and native
25
+ export const IF_EXISTS = 3.542694326329068e-103;
26
+ const CALLBACK_THREW = {};
27
+ const LocalSharedArrayBuffer = typeof Deno != 'undefined' ? ArrayBuffer : SharedArrayBuffer; // Deno can't handle SharedArrayBuffer as an FFI argument due to https://github.com/denoland/deno/issues/12678
28
+ const ByteArray = typeof Buffer != 'undefined' ? function(buffer) { return Buffer.from(buffer) } : Uint8Array;
29
+ const queueTask = typeof setImmediate != 'undefined' ? setImmediate : setTimeout; // TODO: Or queueMicrotask?
30
+ //let debugLog = []
31
+ const WRITE_BUFFER_SIZE = 0x10000;
32
+ var log = [];
33
+ export function addWriteMethods(LMDBStore, { env, fixedBuffer, resetReadTxn, useWritemap, maxKeySize,
34
+ eventTurnBatching, txnStartThreshold, batchStartThreshold, overlappingSync, commitDelay, separateFlushed, maxFlushDelay }) {
35
+ // stands for write instructions
36
+ var dynamicBytes;
37
+ function allocateInstructionBuffer(lastPosition) {
38
+ // Must use a shared buffer on older node in order to use Atomics, and it is also more correct since we are
39
+ // indeed accessing and modifying it from another thread (in C). However, Deno can't handle it for
40
+ // FFI so aliased above
41
+ let buffer = new LocalSharedArrayBuffer(WRITE_BUFFER_SIZE);
42
+ let lastBytes = dynamicBytes;
43
+ dynamicBytes = new ByteArray(buffer);
44
+ let uint32 = dynamicBytes.uint32 = new Uint32Array(buffer, 0, WRITE_BUFFER_SIZE >> 2);
45
+ uint32[2] = 0;
46
+ dynamicBytes.float64 = new Float64Array(buffer, 0, WRITE_BUFFER_SIZE >> 3);
47
+ buffer.address = getBufferAddress(dynamicBytes);
48
+ uint32.address = buffer.address + uint32.byteOffset;
49
+ dynamicBytes.position = 1; // we start at position 1 to save space for writing the txn id before the txn delimiter
50
+ if (lastPosition) {
51
+ lastBytes.float64[lastPosition + 1] = dynamicBytes.uint32.address + (dynamicBytes.position << 3);
52
+ lastBytes.uint32[lastPosition << 1] = 3; // pointer instruction
53
+ }
54
+ return dynamicBytes;
55
+ }
56
+ var newBufferThreshold = (WRITE_BUFFER_SIZE - maxKeySize - 64) >> 3; // need to reserve more room if we do inline values
57
+ var outstandingWriteCount = 0;
58
+ var startAddress = 0;
59
+ var writeTxn = null;
60
+ var committed;
61
+ var abortedNonChildTransactionWarn;
62
+ var nextTxnCallbacks = [];
63
+ var commitPromise, flushPromise, flushResolvers = [], batchFlushResolvers = [];
64
+ commitDelay = commitDelay || 0;
65
+ eventTurnBatching = eventTurnBatching === false ? false : true;
66
+ var enqueuedCommit;
67
+ var afterCommitCallbacks = [];
68
+ var beforeCommitCallbacks = [];
69
+ var enqueuedEventTurnBatch;
70
+ var batchDepth = 0;
71
+ var lastWritePromise;
72
+ var writeBatchStart, outstandingBatchCount, lastSyncTxnFlush, lastFlushTimeout, lastFlushCallback;
73
+ var hasUnresolvedTxns;
74
+ txnStartThreshold = txnStartThreshold || 5;
75
+ batchStartThreshold = batchStartThreshold || 1000;
76
+ maxFlushDelay = maxFlushDelay || 500;
77
+
78
+ allocateInstructionBuffer();
79
+ dynamicBytes.uint32[2] = TXN_DELIMITER | TXN_COMMITTED | TXN_FLUSHED;
80
+ var txnResolution, nextResolution = {
81
+ uint32: dynamicBytes.uint32, flagPosition: 2, flag: 0, valueBuffer: null, next: null, meta: null };
82
+ var uncommittedResolution = {
83
+ uint32: null, flagPosition: 2, flag: 0, valueBuffer: null, next: nextResolution, meta: null };
84
+ var unwrittenResolution = nextResolution;
85
+ var lastPromisedResolution = uncommittedResolution;
86
+ var lastQueuedResolution = uncommittedResolution;
87
+ function writeInstructions(flags, store, key, value, version, ifVersion) {
88
+ let writeStatus;
89
+ let targetBytes, position, encoder;
90
+ let valueSize, valueBuffer, valueBufferStart;
91
+ if (flags & 2) {
92
+ // encode first in case we have to write a shared structure
93
+ encoder = store.encoder;
94
+ if (value && value['\x10binary-data\x02'])
95
+ valueBuffer = value['\x10binary-data\x02'];
96
+ else if (encoder) {
97
+ if (encoder.copyBuffers) // use this as indicator for support buffer reuse for now
98
+ valueBuffer = encoder.encode(value, REUSE_BUFFER_MODE | (writeTxn ? RESET_BUFFER_MODE : 0)); // in addition, if we are writing sync, after using, we can immediately reset the encoder's position to reuse that space, which can improve performance
99
+ else { // various other encoders, including JSON.stringify, that might serialize to a string
100
+ valueBuffer = encoder.encode(value);
101
+ if (typeof valueBuffer == 'string')
102
+ valueBuffer = Buffer.from(valueBuffer); // TODO: Would be nice to write strings inline in the instructions
103
+ }
104
+ } else if (typeof value == 'string') {
105
+ valueBuffer = Buffer.from(value); // TODO: Would be nice to write strings inline in the instructions
106
+ } else if (value instanceof Uint8Array)
107
+ valueBuffer = value;
108
+ else
109
+ throw new Error('Invalid value to put in database ' + value + ' (' + (typeof value) +'), consider using encoder');
110
+ valueBufferStart = valueBuffer.start;
111
+ if (valueBufferStart > -1) // if we have buffers with start/end position
112
+ valueSize = valueBuffer.end - valueBufferStart; // size
113
+ else
114
+ valueSize = valueBuffer.length;
115
+ if (store.dupSort && valueSize > maxKeySize)
116
+ throw new Error('The value is larger than the maximum size (' + maxKeySize + ') for a value in a dupSort database');
117
+ } else
118
+ valueSize = 0;
119
+ if (writeTxn) {
120
+ targetBytes = fixedBuffer;
121
+ position = 0;
122
+ } else {
123
+ if (eventTurnBatching && !enqueuedEventTurnBatch && batchDepth == 0) {
124
+ enqueuedEventTurnBatch = queueTask(() => {
125
+ try {
126
+ for (let i = 0, l = beforeCommitCallbacks.length; i < l; i++) {
127
+ try {
128
+ beforeCommitCallbacks[i]();
129
+ } catch(error) {
130
+ console.error('In beforecommit callback', error);
131
+ }
132
+ }
133
+ } catch(error) {
134
+ console.error(error);
135
+ }
136
+ enqueuedEventTurnBatch = null;
137
+ batchDepth--;
138
+ finishBatch();
139
+ if (writeBatchStart)
140
+ writeBatchStart(); // TODO: When we support delay start of batch, optionally don't delay this
141
+ });
142
+ commitPromise = null; // reset the commit promise, can't know if it is really a new transaction prior to finishWrite being called
143
+ flushPromise = null;
144
+ writeBatchStart = writeInstructions(1, store);
145
+ outstandingBatchCount = 0;
146
+ batchDepth++;
147
+ }
148
+ targetBytes = dynamicBytes;
149
+ position = targetBytes.position;
150
+ }
151
+ let uint32 = targetBytes.uint32, float64 = targetBytes.float64;
152
+ let flagPosition = position << 1; // flagPosition is the 32-bit word starting position
153
+
154
+ // don't increment position until we are sure we don't have any key writing errors
155
+ if (!uint32) {
156
+ throw new Error('Internal buffers have been corrupted');
157
+ }
158
+ uint32[flagPosition + 1] = store.db.dbi;
159
+ if (flags & 4) {
160
+ let keyStartPosition = (position << 3) + 12;
161
+ let endPosition;
162
+ try {
163
+ endPosition = store.writeKey(key, targetBytes, keyStartPosition);
164
+ if (!(keyStartPosition < endPosition) && (flags & 0xf) != 12)
165
+ throw new Error('Invalid key or zero length key is not allowed in LMDB ' + key)
166
+ } catch(error) {
167
+ targetBytes.fill(0, keyStartPosition);
168
+ if (error.name == 'RangeError')
169
+ error = new Error('Key size is larger than the maximum key size (' + maxKeySize + ')');
170
+ throw error;
171
+ }
172
+ let keySize = endPosition - keyStartPosition;
173
+ if (keySize > maxKeySize) {
174
+ targetBytes.fill(0, keyStartPosition); // restore zeros
175
+ throw new Error('Key size is larger than the maximum key size (' + maxKeySize + ')');
176
+ }
177
+ uint32[flagPosition + 2] = keySize;
178
+ position = (endPosition + 16) >> 3;
179
+ if (flags & 2) {
180
+ let mustCompress;
181
+ if (valueBufferStart > -1) { // if we have buffers with start/end position
182
+ // record pointer to value buffer
183
+ float64[position] = (valueBuffer.address ||
184
+ (valueBuffer.address = getAddress(valueBuffer.buffer))) + valueBufferStart;
185
+ mustCompress = valueBuffer[valueBufferStart] >= 250; // this is the compression indicator, so we must compress
186
+ } else {
187
+ let valueArrayBuffer = valueBuffer.buffer;
188
+ // record pointer to value buffer
189
+ let address = (valueArrayBuffer.address ||
190
+ (valueBuffer.length === 0 ? 0 : // externally allocated buffers of zero-length with the same non-null-pointer can crash node, #161
191
+ valueArrayBuffer.address = getAddress(valueArrayBuffer)))
192
+ + valueBuffer.byteOffset;
193
+ if (address <= 0 && valueBuffer.length > 0)
194
+ console.error('Supplied buffer had an invalid address', address);
195
+ float64[position] = address;
196
+ mustCompress = valueBuffer[0] >= 250; // this is the compression indicator, so we must compress
197
+ }
198
+ uint32[(position++ << 1) - 1] = valueSize;
199
+ if (store.compression && (valueSize >= store.compression.threshold || mustCompress)) {
200
+ flags |= 0x100000;
201
+ float64[position] = store.compression.address;
202
+ if (!writeTxn)
203
+ compress(env.address, uint32.address + (position << 3), () => {
204
+ // this is never actually called in NodeJS, just use to pin the buffer in memory until it is finished
205
+ // and is a no-op in Deno
206
+ if (!float64)
207
+ throw new Error('No float64 available');
208
+ });
209
+ position++;
210
+ }
211
+ }
212
+ if (ifVersion !== undefined) {
213
+ if (ifVersion === null)
214
+ flags |= 0x10; // if it does not exist, MDB_NOOVERWRITE
215
+ else {
216
+ flags |= 0x100;
217
+ float64[position++] = ifVersion;
218
+ }
219
+ }
220
+ if (version !== undefined) {
221
+ flags |= 0x200;
222
+ float64[position++] = version || 0;
223
+ }
224
+ } else
225
+ position++;
226
+ targetBytes.position = position;
227
+ if (writeTxn) {
228
+ uint32[0] = flags;
229
+ write(env.address, uint32.address);
230
+ return () => (uint32[0] & FAILED_CONDITION) ? SYNC_PROMISE_FAIL : SYNC_PROMISE_SUCCESS;
231
+ }
232
+ // if we ever use buffers that haven't been zero'ed, need to clear out the next slot like this:
233
+ // uint32[position << 1] = 0 // clear out the next slot
234
+ let nextUint32;
235
+ if (position > newBufferThreshold) {
236
+ // make new buffer and make pointer to it
237
+ let lastPosition = position;
238
+ targetBytes = allocateInstructionBuffer(position);
239
+ position = targetBytes.position;
240
+ nextUint32 = targetBytes.uint32;
241
+ } else
242
+ nextUint32 = uint32;
243
+ let resolution = nextResolution;
244
+ // create the placeholder next resolution
245
+ nextResolution = resolution.next = { // we try keep resolutions exactly the same object type
246
+ uint32: nextUint32,
247
+ flagPosition: position << 1,
248
+ flag: 0, // TODO: eventually eliminate this, as we can probably signify HAS_TXN/NO_RESOLVE/FAILED_CONDITION in upper bits
249
+ valueBuffer: fixedBuffer, // these are all just placeholders so that we have the right hidden class initially allocated
250
+ next: null,
251
+ meta: null,
252
+ };
253
+ lastQueuedResolution = resolution;
254
+
255
+ let writtenBatchDepth = batchDepth;
256
+
257
+ return (callback) => {
258
+ if (writtenBatchDepth) {
259
+ // if we are in a batch, the transaction can't close, so we do the faster,
260
+ // but non-deterministic updates, knowing that the write thread can
261
+ // just poll for the status change if we miss a status update
262
+ writeStatus = uint32[flagPosition];
263
+ uint32[flagPosition] = flags;
264
+ //writeStatus = Atomics.or(uint32, flagPosition, flags)
265
+ if (writeBatchStart && !writeStatus) {
266
+ outstandingBatchCount += 1 + (valueSize >> 12);
267
+ if (outstandingBatchCount > batchStartThreshold) {
268
+ outstandingBatchCount = 0;
269
+ writeBatchStart();
270
+ writeBatchStart = null;
271
+ }
272
+ }
273
+ } else // otherwise the transaction could end at any time and we need to know the
274
+ // deterministically if it is ending, so we can reset the commit promise
275
+ // so we use the slower atomic operation
276
+ writeStatus = Atomics.or(uint32, flagPosition, flags);
277
+
278
+ outstandingWriteCount++;
279
+ if (writeStatus & TXN_DELIMITER) {
280
+ commitPromise = null; // TODO: Don't reset these if this comes from the batch start operation on an event turn batch
281
+ flushPromise = null;
282
+ flushResolvers = [];
283
+ queueCommitResolution(resolution);
284
+ if (!startAddress) {
285
+ startAddress = uint32.address + (flagPosition << 2);
286
+ }
287
+ }
288
+ if (!writtenBatchDepth && batchFlushResolvers.length > 0) {
289
+ flushResolvers.push(...batchFlushResolvers);
290
+ batchFlushResolvers = [];
291
+ }
292
+ if (!flushPromise && overlappingSync) {
293
+ flushPromise = new Promise(resolve => {
294
+ if (writtenBatchDepth) {
295
+ batchFlushResolvers.push(resolve);
296
+ } else {
297
+ flushResolvers.push(resolve);
298
+ }
299
+ });
300
+ }
301
+ if (writeStatus & WAITING_OPERATION) { // write thread is waiting
302
+ write(env.address, 0);
303
+ }
304
+ if (outstandingWriteCount > BACKPRESSURE_THRESHOLD && !writeBatchStart) {
305
+ if (!backpressureArray)
306
+ backpressureArray = new Int32Array(new SharedArrayBuffer(4), 0, 1);
307
+ Atomics.wait(backpressureArray, 0, 0, Math.round(outstandingWriteCount / BACKPRESSURE_THRESHOLD));
308
+ }
309
+ if (startAddress) {
310
+ if (eventTurnBatching)
311
+ startWriting(); // start writing immediately because this has already been batched/queued
312
+ else if (!enqueuedCommit && txnStartThreshold) {
313
+ enqueuedCommit = (commitDelay == 0 && typeof setImmediate != 'undefined') ? setImmediate(() => startWriting()) : setTimeout(() => startWriting(), commitDelay);
314
+ } else if (outstandingWriteCount > txnStartThreshold)
315
+ startWriting();
316
+ }
317
+
318
+ if ((outstandingWriteCount & 7) === 0)
319
+ resolveWrites();
320
+
321
+ if (store.cache) {
322
+ resolution.meta = {
323
+ key,
324
+ store,
325
+ valueSize: valueBuffer ? valueBuffer.length : 0,
326
+ };
327
+ }
328
+ resolution.valueBuffer = valueBuffer;
329
+
330
+ if (callback) {
331
+ if (callback === IF_EXISTS)
332
+ ifVersion = IF_EXISTS;
333
+ else {
334
+ let meta = resolution.meta || (resolution.meta = {});
335
+ meta.reject = callback;
336
+ meta.resolve = (value) => callback(null, value);
337
+ return;
338
+ }
339
+ }
340
+ if (ifVersion === undefined) {
341
+ if (writtenBatchDepth > 1) {
342
+ if (!resolution.flag && !store.cache)
343
+ resolution.flag = NO_RESOLVE;
344
+ return PROMISE_SUCCESS; // or return undefined?
345
+ }
346
+ if (commitPromise) {
347
+ if (!resolution.flag)
348
+ resolution.flag = NO_RESOLVE;
349
+ } else {
350
+ commitPromise = new Promise((resolve, reject) => {
351
+ let meta = resolution.meta || (resolution.meta = {});
352
+ meta.resolve = resolve;
353
+ resolve.unconditional = true;
354
+ meta.reject = reject;
355
+ });
356
+ if (separateFlushed)
357
+ commitPromise.flushed = overlappingSync ? flushPromise : commitPromise;
358
+ }
359
+ return commitPromise;
360
+ }
361
+ lastWritePromise = new Promise((resolve, reject) => {
362
+ let meta = resolution.meta || (resolution.meta = {});
363
+ meta.resolve = resolve;
364
+ meta.reject = reject;
365
+ });
366
+ if (separateFlushed)
367
+ lastWritePromise.flushed = overlappingSync ? flushPromise : lastWritePromise;
368
+ return lastWritePromise;
369
+ };
370
+ }
371
+ let committedFlushResolvers, lastSync = Promise.resolve()
372
+ function startWriting() {
373
+ if (enqueuedCommit) {
374
+ clearImmediate(enqueuedCommit);
375
+ enqueuedCommit = null;
376
+ }
377
+ let resolvers = flushResolvers;
378
+ let start = Date.now();
379
+ env.startWriting(startAddress, (status) => {
380
+ if (dynamicBytes.uint32[dynamicBytes.position << 1] & TXN_DELIMITER)
381
+ queueCommitResolution(nextResolution);
382
+
383
+ resolveWrites(true);
384
+ switch (status) {
385
+ case 0:
386
+ for (let resolver of resolvers) {
387
+ resolver();
388
+ }
389
+ break;
390
+ case 1:
391
+ break;
392
+ case 2:
393
+ hasUnresolvedTxns = false;
394
+ executeTxnCallbacks();
395
+ return hasUnresolvedTxns;
396
+ break;
397
+ default:
398
+ try {
399
+ lmdbError(status);
400
+ } catch(error) {
401
+ console.error(error);
402
+ if (commitRejectPromise) {
403
+ commitRejectPromise.reject(error);
404
+ commitRejectPromise = null;
405
+ }
406
+ }
407
+ }
408
+ });
409
+ startAddress = 0;
410
+ }
411
+
412
+ function queueCommitResolution(resolution) {
413
+ if (!(resolution.flag & HAS_TXN)) {
414
+ resolution.flag = HAS_TXN;
415
+ if (txnResolution) {
416
+ txnResolution.nextTxn = resolution;
417
+ //outstandingWriteCount = 0
418
+ }
419
+ else
420
+ txnResolution = resolution;
421
+ }
422
+ }
423
+ var TXN_DONE = TXN_COMMITTED | TXN_FAILED;
424
+ function resolveWrites(async) {
425
+ // clean up finished instructions
426
+ let instructionStatus;
427
+ while ((instructionStatus = unwrittenResolution.uint32[unwrittenResolution.flagPosition])
428
+ & 0x1000000) {
429
+ if (unwrittenResolution.callbacks) {
430
+ nextTxnCallbacks.push(unwrittenResolution.callbacks);
431
+ unwrittenResolution.callbacks = null;
432
+ }
433
+ outstandingWriteCount--;
434
+ if (unwrittenResolution.flag !== HAS_TXN) {
435
+ if (unwrittenResolution.flag === NO_RESOLVE && !unwrittenResolution.meta) {
436
+ // in this case we can completely remove from the linked list, clearing more memory
437
+ lastPromisedResolution.next = unwrittenResolution = unwrittenResolution.next;
438
+ continue;
439
+ }
440
+ unwrittenResolution.uint32 = null;
441
+ }
442
+ unwrittenResolution.valueBuffer = null;
443
+ unwrittenResolution.flag = instructionStatus;
444
+ lastPromisedResolution = unwrittenResolution;
445
+ unwrittenResolution = unwrittenResolution.next;
446
+ }
447
+ while (txnResolution &&
448
+ (instructionStatus = txnResolution.uint32[txnResolution.flagPosition] & TXN_DONE)) {
449
+ if (instructionStatus & TXN_FAILED)
450
+ rejectCommit();
451
+ else
452
+ resolveCommit(async);
453
+ }
454
+ }
455
+
456
+ function resolveCommit(async) {
457
+ afterCommit(txnResolution.uint32[txnResolution.flagPosition - 1]);
458
+ if (async)
459
+ resetReadTxn();
460
+ else
461
+ queueMicrotask(resetReadTxn); // TODO: only do this if there are actually committed writes?
462
+ do {
463
+ if (uncommittedResolution.meta && uncommittedResolution.meta.resolve) {
464
+ let resolve = uncommittedResolution.meta.resolve;
465
+ if (uncommittedResolution.flag & FAILED_CONDITION && !resolve.unconditional)
466
+ resolve(false);
467
+ else
468
+ resolve(true);
469
+ }
470
+ } while((uncommittedResolution = uncommittedResolution.next) && uncommittedResolution != txnResolution)
471
+ txnResolution = txnResolution.nextTxn;
472
+ }
473
+ var commitRejectPromise;
474
+ function rejectCommit() {
475
+ afterCommit();
476
+ if (!commitRejectPromise) {
477
+ let rejectFunction;
478
+ commitRejectPromise = new Promise((resolve, reject) => rejectFunction = reject);
479
+ commitRejectPromise.reject = rejectFunction;
480
+ }
481
+ do {
482
+ if (uncommittedResolution.meta && uncommittedResolution.meta.reject) {
483
+ let flag = uncommittedResolution.flag & 0xf;
484
+ let error = new Error("Commit failed (see commitError for details)");
485
+ error.commitError = commitRejectPromise;
486
+ uncommittedResolution.meta.reject(error);
487
+ }
488
+ } while((uncommittedResolution = uncommittedResolution.next) && uncommittedResolution != txnResolution)
489
+ txnResolution = txnResolution.nextTxn;
490
+ }
491
+ function atomicStatus(uint32, flagPosition, newStatus) {
492
+ if (batchDepth) {
493
+ // if we are in a batch, the transaction can't close, so we do the faster,
494
+ // but non-deterministic updates, knowing that the write thread can
495
+ // just poll for the status change if we miss a status update
496
+ let writeStatus = uint32[flagPosition];
497
+ uint32[flagPosition] = newStatus;
498
+ return writeStatus;
499
+ //return Atomics.or(uint32, flagPosition, newStatus)
500
+ } else // otherwise the transaction could end at any time and we need to know the
501
+ // deterministically if it is ending, so we can reset the commit promise
502
+ // so we use the slower atomic operation
503
+ try {
504
+ return Atomics.or(uint32, flagPosition, newStatus);
505
+ } catch(error) {
506
+ console.error(error);
507
+ return;
508
+ }
509
+ }
510
+ function afterCommit(txnId) {
511
+ for (let i = 0, l = afterCommitCallbacks.length; i < l; i++) {
512
+ try {
513
+ afterCommitCallbacks[i]({next: uncommittedResolution, last: txnResolution, txnId});
514
+ } catch(error) {
515
+ console.error('In aftercommit callback', error);
516
+ }
517
+ }
518
+ }
519
+ async function executeTxnCallbacks() {
520
+ env.writeTxn = writeTxn = { write: true };
521
+ nextTxnCallbacks.isExecuting = true;
522
+ for (let i = 0; i < nextTxnCallbacks.length; i++) {
523
+ let txnCallbacks = nextTxnCallbacks[i];
524
+ for (let j = 0, l = txnCallbacks.length; j < l; j++) {
525
+ let userTxnCallback = txnCallbacks[j];
526
+ let asChild = userTxnCallback.asChild;
527
+ if (asChild) {
528
+ env.beginTxn(1); // abortable
529
+ let parentTxn = writeTxn;
530
+ env.writeTxn = writeTxn = { write: true };
531
+ try {
532
+ let result = userTxnCallback.callback();
533
+ if (result && result.then) {
534
+ hasUnresolvedTxns = true;
535
+ await result;
536
+ }
537
+ if (result === ABORT)
538
+ env.abortTxn();
539
+ else
540
+ env.commitTxn();
541
+ clearWriteTxn(parentTxn);
542
+ txnCallbacks[j] = result;
543
+ } catch(error) {
544
+ clearWriteTxn(parentTxn);
545
+ env.abortTxn();
546
+ txnError(error, txnCallbacks, j);
547
+ }
548
+ } else {
549
+ try {
550
+ let result = userTxnCallback();
551
+ txnCallbacks[j] = result;
552
+ if (result && result.then) {
553
+ hasUnresolvedTxns = true;
554
+ await result;
555
+ }
556
+ } catch(error) {
557
+ txnError(error, txnCallbacks, j);
558
+ }
559
+ }
560
+ }
561
+ }
562
+ nextTxnCallbacks = [];
563
+ clearWriteTxn(null);
564
+ if (hasUnresolvedTxns) {
565
+ env.resumeWriting();
566
+ }
567
+ function txnError(error, txnCallbacks, i) {
568
+ (txnCallbacks.errors || (txnCallbacks.errors = []))[i] = error;
569
+ txnCallbacks[i] = CALLBACK_THREW;
570
+ }
571
+ }
572
+ function finishBatch() {
573
+ dynamicBytes.uint32[(dynamicBytes.position + 1) << 1] = 0; // clear out the next slot
574
+ let writeStatus = atomicStatus(dynamicBytes.uint32, (dynamicBytes.position++) << 1, 2); // atomically write the end block
575
+ nextResolution.flagPosition += 2;
576
+ if (writeStatus & WAITING_OPERATION) {
577
+ write(env.address, 0);
578
+ }
579
+ if (dynamicBytes.position > newBufferThreshold) {
580
+ allocateInstructionBuffer(dynamicBytes.position);
581
+ nextResolution.flagPosition = dynamicBytes.position << 1;
582
+ nextResolution.uint32 = dynamicBytes.uint32;
583
+ }
584
+ }
585
+ function clearWriteTxn(parentTxn) {
586
+ // TODO: We might actually want to track cursors in a write txn and manually
587
+ // close them.
588
+ if (writeTxn && writeTxn.refCount > 0)
589
+ writeTxn.isDone = true;
590
+ env.writeTxn = writeTxn = parentTxn || null;
591
+ }
592
+ Object.assign(LMDBStore.prototype, {
593
+ put(key, value, versionOrOptions, ifVersion) {
594
+ let callback, flags = 15, type = typeof versionOrOptions;
595
+ if (type == 'object' && versionOrOptions) {
596
+ if (versionOrOptions.noOverwrite)
597
+ flags |= 0x10;
598
+ if (versionOrOptions.noDupData)
599
+ flags |= 0x20;
600
+ if (versionOrOptions.append)
601
+ flags |= 0x20000;
602
+ if (versionOrOptions.ifVersion != undefined)
603
+ ifVersion = versionOrOptions.ifVersion;
604
+ versionOrOptions = versionOrOptions.version;
605
+ if (typeof ifVersion == 'function')
606
+ callback = ifVersion;
607
+ } else if (type == 'function') {
608
+ callback = versionOrOptions;
609
+ }
610
+ return writeInstructions(flags, this, key, value, this.useVersions ? versionOrOptions || 0 : undefined, ifVersion)(callback);
611
+ },
612
+ remove(key, ifVersionOrValue, callback) {
613
+ let flags = 13;
614
+ let ifVersion, value;
615
+ if (ifVersionOrValue !== undefined) {
616
+ if (typeof ifVersionOrValue == 'function')
617
+ callback = ifVersionOrValue;
618
+ else if (ifVersionOrValue === IF_EXISTS && !callback)
619
+ // we have a handler for IF_EXISTS in the callback handler for remove
620
+ callback = ifVersionOrValue;
621
+ else if (this.useVersions)
622
+ ifVersion = ifVersionOrValue;
623
+ else {
624
+ flags = 14;
625
+ value = ifVersionOrValue;
626
+ }
627
+ }
628
+ return writeInstructions(flags, this, key, value, undefined, ifVersion)(callback);
629
+ },
630
+ del(key, options, callback) {
631
+ return this.remove(key, options, callback);
632
+ },
633
+ ifNoExists(key, callback) {
634
+ return this.ifVersion(key, null, callback);
635
+ },
636
+ ifVersion(key, version, callback, options) {
637
+ if (!callback) {
638
+ return new Batch((operations, callback) => {
639
+ let promise = this.ifVersion(key, version, operations, options);
640
+ if (callback)
641
+ promise.then(callback);
642
+ return promise;
643
+ });
644
+ }
645
+ if (writeTxn) {
646
+ if (version === undefined || this.doesExist(key, version)) {
647
+ callback();
648
+ return SYNC_PROMISE_SUCCESS;
649
+ }
650
+ return SYNC_PROMISE_FAIL;
651
+ }
652
+ let flags = key === undefined || version === undefined ? 1 : 4;
653
+ if (options?.ifLessThan)
654
+ flags |= CONDITIONAL_VERSION_LESS_THAN;
655
+ if (options?.allowNotFound)
656
+ flags |= CONDITIONAL_ALLOW_NOTFOUND;
657
+ let finishStartWrite = writeInstructions(flags, this, key, undefined, undefined, version);
658
+ let promise;
659
+ batchDepth += 2;
660
+ if (batchDepth > 2)
661
+ promise = finishStartWrite();
662
+ else {
663
+ writeBatchStart = () => {
664
+ promise = finishStartWrite();
665
+ };
666
+ outstandingBatchCount = 0;
667
+ }
668
+ try {
669
+ if (typeof callback === 'function') {
670
+ callback();
671
+ } else {
672
+ for (let i = 0, l = callback.length; i < l; i++) {
673
+ let operation = callback[i];
674
+ this[operation.type](operation.key, operation.value);
675
+ }
676
+ }
677
+ } finally {
678
+ if (!promise) {
679
+ finishBatch();
680
+ batchDepth -= 2;
681
+ promise = finishStartWrite(); // finish write once all the operations have been written (and it hasn't been written prematurely)
682
+ writeBatchStart = null;
683
+ } else {
684
+ batchDepth -= 2;
685
+ finishBatch();
686
+ }
687
+ }
688
+ return promise;
689
+ },
690
+ batch(callbackOrOperations) {
691
+ return this.ifVersion(undefined, undefined, callbackOrOperations);
692
+ },
693
+ drop(callback) {
694
+ return writeInstructions(1024 + 12, this, Buffer.from([]), undefined, undefined, undefined)(callback);
695
+ },
696
+ clearAsync(callback) {
697
+ if (this.encoder) {
698
+ if (this.encoder.clearSharedData)
699
+ this.encoder.clearSharedData()
700
+ else if (this.encoder.structures)
701
+ this.encoder.structures = []
702
+ }
703
+ return writeInstructions(12, this, Buffer.from([]), undefined, undefined, undefined)(callback);
704
+ },
705
+ _triggerError() {
706
+ finishBatch();
707
+ },
708
+
709
+ putSync(key, value, versionOrOptions, ifVersion) {
710
+ if (writeTxn)
711
+ return this.put(key, value, versionOrOptions, ifVersion) === SYNC_PROMISE_SUCCESS;
712
+ else
713
+ return this.transactionSync(() =>
714
+ this.put(key, value, versionOrOptions, ifVersion) === SYNC_PROMISE_SUCCESS, overlappingSync? 0x10002 : 2); // non-abortable, async flush
715
+ },
716
+ removeSync(key, ifVersionOrValue) {
717
+ if (writeTxn)
718
+ return this.remove(key, ifVersionOrValue) === SYNC_PROMISE_SUCCESS;
719
+ else
720
+ return this.transactionSync(() =>
721
+ this.remove(key, ifVersionOrValue) === SYNC_PROMISE_SUCCESS, overlappingSync? 0x10002 : 2); // non-abortable, async flush
722
+ },
723
+ transaction(callback) {
724
+ if (writeTxn && !nextTxnCallbacks.isExecuting) {
725
+ if (!useWritemap)
726
+ return this.childTransaction(callback);
727
+ let result = callback();
728
+ if (result == ABORT && !abortedNonChildTransactionWarn) {
729
+ console.warn('Can not abort a transaction inside another transaction with ' + (this.cache ? 'caching enabled' : 'useWritemap enabled'));
730
+ abortedNonChildTransactionWarn = true;
731
+ }
732
+ return result;
733
+ }
734
+ return this.transactionAsync(callback, true);
735
+ },
736
+ childTransaction(callback) {
737
+ if (useWritemap)
738
+ throw new Error('Child transactions are not supported in writemap mode');
739
+ if (writeTxn) {
740
+ let parentTxn = writeTxn;
741
+ let thisTxn = env.writeTxn = writeTxn = { write: true };
742
+ env.beginTxn(1); // abortable
743
+ let callbackDone, finishTxn;
744
+ try {
745
+ return writeTxn.childResults = when(callback(), finishTxn = (result) => {
746
+ if (writeTxn !== thisTxn) // need to wait for child txn to finish asynchronously
747
+ return writeTxn.childResults.then(() => finishTxn(result));
748
+ callbackDone = true;
749
+ if (result === ABORT)
750
+ env.abortTxn();
751
+ else
752
+ env.commitTxn();
753
+ clearWriteTxn(parentTxn);
754
+ return result;
755
+ }, (error) => {
756
+ env.abortTxn();
757
+ clearWriteTxn(parentTxn);
758
+ throw error;
759
+ });
760
+ } catch(error) {
761
+ if (!callbackDone)
762
+ env.abortTxn();
763
+ clearWriteTxn(parentTxn);
764
+ throw error;
765
+ }
766
+ }
767
+ return this.transactionAsync(callback, true);
768
+ },
769
+ transactionAsync(callback, asChild) {
770
+ let txnIndex;
771
+ let txnCallbacks;
772
+ if (lastQueuedResolution.callbacks) {
773
+ txnCallbacks = lastQueuedResolution.callbacks;
774
+ txnIndex = txnCallbacks.push(asChild ? { callback, asChild } : callback) - 1;
775
+ } else if (nextTxnCallbacks.isExecuting) {
776
+ txnCallbacks = [asChild ? { callback, asChild } : callback];
777
+ txnCallbacks.results = commitPromise;
778
+ nextTxnCallbacks.push(txnCallbacks);
779
+ txnIndex = 0;
780
+ } else {
781
+ if (writeTxn)
782
+ throw new Error('Can not enqueue transaction during write txn');
783
+ let finishWrite = writeInstructions(8 | (this.strictAsyncOrder ? 0x100000 : 0), this);
784
+ txnCallbacks = [asChild ? { callback, asChild } : callback];
785
+ lastQueuedResolution.callbacks = txnCallbacks;
786
+ lastQueuedResolution.id = Math.random();
787
+ txnCallbacks.results = finishWrite();
788
+ txnIndex = 0;
789
+ }
790
+ return txnCallbacks.results.then((results) => {
791
+ let result = txnCallbacks[txnIndex];
792
+ if (result === CALLBACK_THREW)
793
+ throw txnCallbacks.errors[txnIndex];
794
+ return result;
795
+ });
796
+ },
797
+ transactionSync(callback, flags) {
798
+ if (writeTxn) {
799
+ if (!useWritemap && (flags == undefined || (flags & 1))) // can't use child transactions in write maps
800
+ // already nested in a transaction, execute as child transaction (if possible) and return
801
+ return this.childTransaction(callback);
802
+ let result = callback(); // else just run in current transaction
803
+ if (result == ABORT && !abortedNonChildTransactionWarn) {
804
+ console.warn('Can not abort a transaction inside another transaction with ' + (this.cache ? 'caching enabled' : 'useWritemap enabled'));
805
+ abortedNonChildTransactionWarn = true;
806
+ }
807
+ return result;
808
+ }
809
+ let callbackDone, finishTxn;
810
+ this.transactions++;
811
+ if (!env.address)
812
+ throw new Error('The database has been closed and you can not transact on it');
813
+ env.beginTxn(flags == undefined ? 3 : flags);
814
+ let thisTxn = writeTxn = env.writeTxn = { write: true };
815
+ try {
816
+ this.emit('begin-transaction');
817
+ return writeTxn.childResults = when(callback(), finishTxn = (result) => {
818
+ if (writeTxn !== thisTxn) // need to wait for child txn to finish asynchronously
819
+ return writeTxn.childResults.then(() => finishTxn(result));
820
+ try {
821
+ callbackDone = true;
822
+ if (result === ABORT)
823
+ env.abortTxn();
824
+ else {
825
+ env.commitTxn();
826
+ resetReadTxn();
827
+ }
828
+ return result;
829
+ } finally {
830
+ clearWriteTxn(null);
831
+ }
832
+ }, (error) => {
833
+ try { env.abortTxn(); } catch(e) {}
834
+ clearWriteTxn(null);
835
+ throw error;
836
+ });
837
+ } catch(error) {
838
+ if (!callbackDone)
839
+ try { env.abortTxn(); } catch(e) {}
840
+ clearWriteTxn(null);
841
+ throw error;
842
+ }
843
+ },
844
+ transactionSyncStart(callback) {
845
+ return this.transactionSync(callback, 0);
846
+ },
847
+ // make the db a thenable/promise-like for when the last commit is committed
848
+ committed: committed = {
849
+ then(onfulfilled, onrejected) {
850
+ if (commitPromise)
851
+ return commitPromise.then(onfulfilled, onrejected);
852
+ if (lastWritePromise) // always resolve to true
853
+ return lastWritePromise.then(() => onfulfilled(true), onrejected);
854
+ return SYNC_PROMISE_SUCCESS.then(onfulfilled, onrejected);
855
+ }
856
+ },
857
+ flushed: {
858
+ // make this a thenable for when the commit is flushed to disk
859
+ then(onfulfilled, onrejected) {
860
+ if (flushPromise)
861
+ flushPromise.hasCallbacks = true
862
+ return Promise.all([flushPromise || committed, lastSyncTxnFlush]).then(onfulfilled, onrejected);
863
+ }
864
+ },
865
+ _endWrites(resolvedPromise, resolvedSyncPromise) {
866
+ this.put = this.remove = this.del = this.batch = this.removeSync = this.putSync = this.transactionAsync = this.drop = this.clearAsync = () => { throw new Error('Database is closed') };
867
+ // wait for all txns to finish, checking again after the current txn is done
868
+ let finalPromise = flushPromise || commitPromise || lastWritePromise;
869
+ if (flushPromise)
870
+ flushPromise.hasCallbacks = true
871
+ let finalSyncPromise = lastSyncTxnFlush;
872
+ if (finalPromise && resolvedPromise != finalPromise ||
873
+ finalSyncPromise && resolvedSyncPromise != finalSyncPromise) {
874
+ return Promise.all([finalPromise, finalSyncPromise]).then(() => this._endWrites(finalPromise, finalSyncPromise), () => this._endWrites(finalPromise, finalSyncPromise));
875
+ }
876
+ Object.defineProperty(env, 'sync', { value: null });
877
+ },
878
+ on(event, callback) {
879
+ if (event == 'beforecommit') {
880
+ eventTurnBatching = true;
881
+ beforeCommitCallbacks.push(callback);
882
+ } else if (event == 'aftercommit')
883
+ afterCommitCallbacks.push(callback);
884
+ else
885
+ super.on(event, callback);
886
+ }
887
+ });
888
+ }
889
+
890
+ class Batch extends Array {
891
+ constructor(callback) {
892
+ super();
893
+ this.callback = callback;
894
+ }
895
+ put(key, value) {
896
+ this.push({ type: 'put', key, value });
897
+ }
898
+ del(key) {
899
+ this.push({ type: 'del', key });
900
+ }
901
+ clear() {
902
+ this.splice(0, this.length);
903
+ }
904
+ write(callback) {
905
+ return this.callback(this, callback);
906
+ }
907
+ }
908
+ export function asBinary(buffer) {
909
+ return {
910
+ ['\x10binary-data\x02']: buffer
911
+ };
912
+ }