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