forked from patorjk/JavaScript-Snake
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdbi.cpp
More file actions
382 lines (349 loc) · 11.9 KB
/
dbi.cpp
File metadata and controls
382 lines (349 loc) · 11.9 KB
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
#include "lmdb-js.h"
#include <cstdio>
using namespace Napi;
void setFlagFromValue(int *flags, int flag, const char *name, bool defaultValue, Object options);
DbiWrap::DbiWrap(const Napi::CallbackInfo& info) : ObjectWrap<DbiWrap>(info) {
this->dbi = 0;
this->keyType = LmdbKeyType::DefaultKey;
this->compression = nullptr;
this->isOpen = false;
this->getFast = false;
this->ew = nullptr;
EnvWrap *ew;
napi_unwrap(info.Env(), info[0], (void**) &ew);
this->env = ew->env;
this->ew = ew;
int flags = info[1].As<Number>();
char* nameBytes;
std::string name;
if (info[2].IsString()) {
name = info[2].As<String>().Utf8Value();
nameBytes = (char*) name.c_str();
} else
nameBytes = nullptr;
LmdbKeyType keyType = (LmdbKeyType) info[3].As<Number>().Int32Value();
Compression* compression;
if (info[4].IsObject())
napi_unwrap(info.Env(), info[4], (void**) &compression);
else
compression = nullptr;
int rc = this->open(flags, nameBytes, flags & HAS_VERSIONS,
keyType, compression);
//if (nameBytes)
//delete nameBytes;
if (rc) {
if (rc == MDB_NOTFOUND)
this->dbi = (MDB_dbi) 0xffffffff;
else {
//delete this;
throwLmdbError(info.Env(), rc);
return;
}
}
info.This().As<Object>().Set("dbi", Number::New(info.Env(), this->dbi));
info.This().As<Object>().Set("address", Number::New(info.Env(), (size_t) this));
}
DbiWrap::~DbiWrap() {
// Imagine the following JS:
// ------------------------
// var dbi1 = env.openDbi({ name: "hello" });
// var dbi2 = env.openDbi({ name: "hello" });
// dbi1.close();
// txn.putString(dbi2, "world");
// -----
// The above DbiWrap objects would both wrap the same MDB_dbi, and if closing the first one called mdb_dbi_close,
// that'd also render the second DbiWrap instance unusable.
//
// For this reason, we will never call mdb_dbi_close
// NOTE: according to LMDB authors, it is perfectly fine if mdb_dbi_close is never called on an MDB_dbi
}
int DbiWrap::open(int flags, char* name, bool hasVersions, LmdbKeyType keyType, Compression* compression) {
MDB_txn* txn = ew->getReadTxn();
this->hasVersions = hasVersions;
this->compression = compression;
this->keyType = keyType;
#ifndef MDB_RPAGE_CACHE
flags &= ~0x100; // remove use versions flag for older lmdb
#endif
this->flags = flags;
int rc = txn ? mdb_dbi_open(txn, name, flags, &this->dbi) : EINVAL;
if (rc)
return rc;
this->isOpen = true;
if (keyType == LmdbKeyType::DefaultKey && name) { // use the fast compare, but can't do it if we have db table/names mixed in
mdb_set_compare(txn, dbi, compareFast);
}
return 0;
}
Value DbiWrap::close(const Napi::CallbackInfo& info) {
if (this->isOpen) {
mdb_dbi_close(this->env, this->dbi);
this->isOpen = false;
this->ew = nullptr;
}
else {
return throwError(info.Env(), "The Dbi is not open, you can't close it.");
}
return info.Env().Undefined();
}
Value DbiWrap::drop(const Napi::CallbackInfo& info) {
int del = 1;
int rc;
if (!this->isOpen) {
return throwError(info.Env(), "The Dbi is not open, you can't drop it.");
}
// Check if the database should be deleted
if (info.Length() == 1 && info[0].IsObject()) {
Napi::Object options = info[0].As<Object>();
// Just free pages
Napi::Value opt = options.Get("justFreePages");
del = opt.IsBoolean() ? !opt.As<Boolean>().Value() : 1;
}
// Drop database
rc = mdb_drop(ew->writeTxn->txn, dbi, del);
if (rc != 0) {
return throwLmdbError(info.Env(), rc);
}
// Only close database if del == 1
if (del == 1) {
isOpen = false;
ew = nullptr;
}
return info.Env().Undefined();
}
Value DbiWrap::stat(const Napi::CallbackInfo& info) {
MDB_stat stat;
mdb_stat(this->ew->getReadTxn(), dbi, &stat);
Object stats = Object::New(info.Env());
stats.Set("pageSize", Number::New(info.Env(), stat.ms_psize));
stats.Set("treeDepth", Number::New(info.Env(), stat.ms_depth));
stats.Set("treeBranchPageCount", Number::New(info.Env(), stat.ms_branch_pages));
stats.Set("treeLeafPageCount", Number::New(info.Env(), stat.ms_leaf_pages));
stats.Set("entryCount", Number::New(info.Env(), stat.ms_entries));
stats.Set("overflowPages", Number::New(info.Env(), stat.ms_overflow_pages));
return stats;
}
int32_t DbiWrap::doGetByBinary(uint32_t keySize, uint32_t ifNotTxnId, int64_t txnWrapAddress) {
char* keyBuffer = ew->keyBuffer;
MDB_txn* txn = ew->getReadTxn(txnWrapAddress);
MDB_val key, data;
key.mv_size = keySize;
key.mv_data = (void*) keyBuffer;
uint32_t* currentTxnId = (uint32_t*) (keyBuffer + 32);
#ifdef MDB_RPAGE_CACHE
int result = mdb_get_with_txn(txn, dbi, &key, &data, (mdb_size_t*) currentTxnId);
#else
int result = mdb_get(txn, dbi, &key, &data);
#endif
if (result) {
if (result > 0)
return -result;
return result;
}
#ifdef MDB_RPAGE_CACHE
if (ifNotTxnId && ifNotTxnId == *currentTxnId)
return -30004;
#endif
result = getVersionAndUncompress(data, this);
bool fits = true;
if (result) {
fits = valToBinaryFast(data, this); // it fits in the global/compression-target buffer
}
if (fits || result == 2 || data.mv_size < SHARED_BUFFER_THRESHOLD) {// result = 2 if it was decompressed
if (data.mv_size < 0x80000000)
return data.mv_size;
*((uint32_t*)keyBuffer) = data.mv_size;
return -30000;
} else {
return EnvWrap::toSharedBuffer(ew->env, (uint32_t*) ew->keyBuffer, data);
}
}
NAPI_FUNCTION(getByBinary) {
ARGS(4)
GET_INT64_ARG(0);
DbiWrap* dw = (DbiWrap*) i64;
uint32_t keySize;
GET_UINT32_ARG(keySize, 1);
uint32_t ifNotTxnId;
GET_UINT32_ARG(ifNotTxnId, 2);
int64_t txnAddress = 0;
napi_status status = napi_get_value_int64(env, args[3], &txnAddress);
RETURN_INT32(dw->doGetByBinary(keySize, ifNotTxnId, txnAddress));
}
uint32_t getByBinaryFFI(double dwPointer, uint32_t keySize, uint32_t ifNotTxnId, uint64_t txnAddress) {
DbiWrap* dw = (DbiWrap*) (size_t) dwPointer;
return dw->doGetByBinary(keySize, ifNotTxnId, txnAddress);
}
napi_finalize noopDbi = [](napi_env, void *, void *) {
// Data belongs to LMDB, we shouldn't free it here
};
NAPI_FUNCTION(getSharedByBinary) {
ARGS(2)
GET_INT64_ARG(0);
DbiWrap* dw = (DbiWrap*) i64;
uint32_t keySize;
GET_UINT32_ARG(keySize, 1);
MDB_val key;
MDB_val data;
key.mv_size = keySize;
key.mv_data = (void*) dw->ew->keyBuffer;
MDB_txn* txn = dw->ew->getReadTxn();
int rc = mdb_get(txn, dw->dbi, &key, &data);
if (rc) {
if (rc == MDB_NOTFOUND) {
RETURN_UNDEFINED;
} else
return throwLmdbError(env, rc);
}
rc = getVersionAndUncompress(data, dw);
napi_create_external_buffer(env, data.mv_size,
(char*) data.mv_data, noopDbi, nullptr, &returnValue);
return returnValue;
}
NAPI_FUNCTION(getStringByBinary) {
ARGS(3)
GET_INT64_ARG(0);
DbiWrap* dw = (DbiWrap*) i64;
uint32_t keySize;
GET_UINT32_ARG(keySize, 1);
int64_t txnAddress = 0;
napi_status status = napi_get_value_int64(env, args[2], &txnAddress);
MDB_val key;
MDB_val data;
key.mv_size = keySize;
key.mv_data = (void*) dw->ew->keyBuffer;
MDB_txn* txn = dw->ew->getReadTxn(txnAddress);
int rc = mdb_get(txn, dw->dbi, &key, &data);
if (rc) {
if (rc == MDB_NOTFOUND) {
RETURN_UNDEFINED;
} else
return throwLmdbError(env, rc);
}
rc = getVersionAndUncompress(data, dw);
if (rc)
napi_create_string_utf8(env, (char*) data.mv_data, data.mv_size, &returnValue);
else
napi_create_int32(env, data.mv_size, &returnValue);
return returnValue;
}
int DbiWrap::prefetch(uint32_t* keys) {
MDB_txn* txn;
mdb_txn_begin(ew->env, nullptr, MDB_RDONLY, &txn);
MDB_val key;
MDB_val data;
unsigned int flags;
mdb_dbi_flags(txn, dbi, &flags);
bool findAllValues = flags & MDB_DUPSORT;
int effected = 0;
bool findDataValue = false;
MDB_cursor *cursor;
int rc = mdb_cursor_open(txn, dbi, &cursor);
if (rc)
return rc;
while((key.mv_size = *keys++) > 0) {
if (key.mv_size == 0xffffffff) {
// it is a pointer to a new buffer
keys = (uint32_t*) (size_t) *((double*) keys); // read as a double pointer
key.mv_size = *keys++;
if (key.mv_size == 0)
break;
}
if (key.mv_size & 0x80000000) {
// indicator of using a data value combination (with dupSort), to be followed by the corresponding key
data.mv_size = key.mv_size & 0x7fffffff;
data.mv_data = (void *) keys;
keys += (data.mv_size + 12) >> 2;
findDataValue = true;
findAllValues = false;
continue;
}
// else standard key
key.mv_data = (void *) keys;
keys += (key.mv_size + 12) >> 2;
int rc = mdb_cursor_get(cursor, &key, &data, findDataValue ? MDB_GET_BOTH : MDB_SET_KEY);
findDataValue = false;
while (!rc) {
// access one byte from each of the pages to ensure they are in the OS cache,
// potentially triggering the hard page fault in this thread
int pages = (data.mv_size + 0xfff) >> 12;
// TODO: Adjust this for the page headers, I believe that makes the first page slightly less 4KB.
for (int i = 0; i < pages; i++) {
effected += *(((uint8_t*)data.mv_data) + (i << 12));
}
if (findAllValues) // in dupsort databases, access the rest of the values
rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT_DUP);
else
rc = 1; // done
}
}
mdb_cursor_close(cursor);
mdb_txn_abort(txn);
return effected;
}
class PrefetchWorker : public AsyncWorker {
public:
PrefetchWorker(DbiWrap* dw, uint32_t* keys, const Function& callback)
: AsyncWorker(callback), dw(dw), keys(keys) {}
void Execute() {
dw->prefetch(keys);
}
void OnOK() {
napi_value result; // we use direct napi call here because node-addon-api interface with throw a fatal error if a worker thread is terminating
napi_call_function(Env(), Env().Undefined(), Callback().Value(), 0, {}, &result);
}
void OnError(const Error& e) {
napi_value result; // we use direct napi call here because node-addon-api interface with throw a fatal error if a worker thread is terminating
napi_value arg = e.Value();
napi_call_function(Env(), Env().Undefined(), Callback().Value(), 1, &arg, &result);
}
private:
DbiWrap* dw;
uint32_t* keys;
};
NAPI_FUNCTION(prefetchNapi) {
ARGS(3)
GET_INT64_ARG(0);
DbiWrap* dw = (DbiWrap*) i64;
napi_get_value_int64(env, args[1], &i64);
uint32_t* keys = (uint32_t*) i64;
PrefetchWorker* worker = new PrefetchWorker(dw, keys, Function(env, args[2]));
worker->Queue();
RETURN_UNDEFINED;
}
void DbiWrap::setupExports(Napi::Env env, Object exports) {
Function DbiClass = DefineClass(env, "Dbi", {
// DbiWrap: Prepare constructor template
// DbiWrap: Add functions to the prototype
DbiWrap::InstanceMethod("close", &DbiWrap::close),
DbiWrap::InstanceMethod("drop", &DbiWrap::drop),
DbiWrap::InstanceMethod("stat", &DbiWrap::stat),
});
exports.Set("Dbi", DbiClass);
EXPORT_NAPI_FUNCTION("getByBinary", getByBinary);
EXPORT_NAPI_FUNCTION("prefetch", prefetchNapi);
EXPORT_NAPI_FUNCTION("getStringByBinary", getStringByBinary);
EXPORT_NAPI_FUNCTION("getSharedByBinary", getSharedByBinary);
EXPORT_FUNCTION_ADDRESS("getByBinaryPtr", getByBinaryFFI);
// TODO: wrap mdb_stat too
}
// This file contains code from the node-lmdb project
// Copyright (c) 2013-2017 Timur Kristóf
// Copyright (c) 2021 Kristopher Tate
// Licensed to you under the terms of the MIT license
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.