-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransaction.cpp
More file actions
468 lines (392 loc) · 15.1 KB
/
transaction.cpp
File metadata and controls
468 lines (392 loc) · 15.1 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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
#include <chrono>
#include <sstream>
#include <thread>
#include "database.h"
#include "db_descriptor.h"
#include "db_handle.h"
#include "db_iterator.h"
#include "macros.h"
#include "transaction.h"
#include "transaction_handle.h"
#include "util.h"
#define UNWRAP_TRANSACTION_HANDLE(fnName) \
std::shared_ptr<TransactionHandle>* txnHandle = nullptr; \
NAPI_STATUS_THROWS(::napi_unwrap(env, jsThis, reinterpret_cast<void**>(&txnHandle))) \
if (!txnHandle || !(*txnHandle)) { \
::napi_throw_error(env, nullptr, fnName " failed: Transaction has already been closed"); \
return nullptr; \
}
#define NAPI_THROW_JS_ERROR(code, message) \
napi_value error; \
rocksdb_js::createJSError(env, code, message, error); \
::napi_throw(env, error); \
return nullptr;
namespace rocksdb_js {
/**
* Creates a new `NativeTransaction` object.
*
* @param env - The NAPI environment.
* @param info - The callback info.
* @returns The new `NativeTransaction` object.
*/
napi_value Transaction::Constructor(napi_env env, napi_callback_info info) {
NAPI_CONSTRUCTOR_ARGV_WITH_DATA("Transaction", 2)
napi_ref exportsRef = reinterpret_cast<napi_ref>(data);
napi_value exports;
NAPI_STATUS_THROWS(::napi_get_reference_value(env, exportsRef, &exports))
napi_value databaseCtor;
NAPI_STATUS_THROWS(::napi_get_named_property(env, exports, "Database", &databaseCtor))
bool isDatabase = false;
NAPI_STATUS_THROWS(::napi_instanceof(env, args[0], databaseCtor, &isDatabase))
bool disableSnapshot = false;
NAPI_STATUS_THROWS(rocksdb_js::getProperty(env, args[1], "disableSnapshot", disableSnapshot));
std::shared_ptr<TransactionHandle>* txnHandle = nullptr;
if (isDatabase) {
std::shared_ptr<DBHandle>* dbHandle = nullptr;
NAPI_STATUS_THROWS(::napi_unwrap(env, args[0], reinterpret_cast<void**>(&dbHandle)))
DEBUG_LOG("Transaction::Constructor Initializing transaction handle with Database instance (dbHandle=%p, use_count=%zu)\n", (*dbHandle).get(), (*dbHandle).use_count())
if (dbHandle == nullptr || !(*dbHandle)->opened()) {
::napi_throw_error(env, nullptr, "Database not open");
return nullptr;
}
txnHandle = new std::shared_ptr<TransactionHandle>(std::make_shared<TransactionHandle>(*dbHandle, disableSnapshot));
if ((*dbHandle)->descriptor->closing.load()) {
::napi_throw_error(env, nullptr, "Database is closing!");
return nullptr;
}
(*dbHandle)->descriptor->transactionAdd(*txnHandle);
} else {
DEBUG_LOG("Transaction::Constructor Using existing transaction handle\n")
napi_value transactionCtor;
NAPI_STATUS_THROWS(::napi_get_named_property(env, exports, "Transaction", &transactionCtor))
bool isTransaction = false;
NAPI_STATUS_THROWS(::napi_instanceof(env, args[0], transactionCtor, &isTransaction))
if (isTransaction) {
DEBUG_LOG("Transaction::Constructor Received Transaction instance\n")
NAPI_STATUS_THROWS(::napi_unwrap(env, args[0], reinterpret_cast<void**>(&txnHandle)))
} else {
napi_valuetype type;
NAPI_STATUS_THROWS(::napi_typeof(env, args[0], &type))
std::string errorMsg = "Invalid context, expected Database or Transaction instance, got type " + std::to_string(type);
::napi_throw_error(env, nullptr, errorMsg.c_str());
return nullptr;
}
}
DEBUG_LOG("Transaction::Constructor txnHandle=%p *txnHandle=%p dbHandle use_count=%zu\n", txnHandle, (*txnHandle).get(), (*txnHandle)->dbHandle.use_count())
try {
NAPI_STATUS_THROWS(::napi_wrap(
env,
jsThis,
reinterpret_cast<void*>(txnHandle),
[](napi_env env, void* data, void* hint) {
DEBUG_LOG("Transaction::Constructor NativeTransaction GC'd txnHandle=%p\n", data)
auto* txnHandle = static_cast<std::shared_ptr<TransactionHandle>*>(data);
if (*txnHandle) {
(*txnHandle).reset();
}
delete txnHandle;
},
nullptr, // finalize_hint
nullptr // result
));
return jsThis;
} catch (const std::exception& e) {
delete txnHandle;
::napi_throw_error(env, nullptr, e.what());
return nullptr;
}
}
/**
* Aborts the transaction.
*/
napi_value Transaction::Abort(napi_env env, napi_callback_info info) {
NAPI_METHOD()
UNWRAP_TRANSACTION_HANDLE("Abort")
TransactionState txnState = (*txnHandle)->state;
if (txnState == TransactionState::Aborted) {
// already aborted
return nullptr;
}
if (txnState == TransactionState::Committing || txnState == TransactionState::Committed) {
NAPI_THROW_JS_ERROR("ERR_ALREADY_COMMITTED", "Transaction has already been committed")
}
(*txnHandle)->state = TransactionState::Aborted;
ROCKSDB_STATUS_THROWS_ERROR_LIKE((*txnHandle)->txn->Rollback(), "Transaction rollback failed")
DEBUG_LOG("Transaction::Abort closing txnHandle=%p\n", (*txnHandle).get())
(*txnHandle)->close();
NAPI_RETURN_UNDEFINED()
}
/**
* State for the `Commit` async work.
*/
struct TransactionCommitState final : BaseAsyncState<std::shared_ptr<TransactionHandle>> {
TransactionCommitState(napi_env env, std::shared_ptr<TransactionHandle> txnHandle)
: BaseAsyncState<std::shared_ptr<TransactionHandle>>(env, txnHandle), timestamp(0) {}
uint64_t timestamp;
};
/**
* Commits the transaction.
*/
napi_value Transaction::Commit(napi_env env, napi_callback_info info) {
NAPI_METHOD_ARGV(2)
napi_value resolve = argv[0];
napi_value reject = argv[1];
UNWRAP_TRANSACTION_HANDLE("Commit")
TransactionCommitState* state = new TransactionCommitState(env, *txnHandle);
NAPI_STATUS_THROWS(::napi_create_reference(env, resolve, 1, &state->resolveRef))
NAPI_STATUS_THROWS(::napi_create_reference(env, reject, 1, &state->rejectRef))
TransactionState txnState = (*txnHandle)->state;
if (txnState == TransactionState::Aborted) {
NAPI_THROW_JS_ERROR("ERR_ALREADY_ABORTED", "Transaction has already been aborted")
}
if (txnState == TransactionState::Committing || txnState == TransactionState::Committed) {
// already committed
napi_value global;
NAPI_STATUS_THROWS(::napi_get_global(env, &global))
NAPI_STATUS_THROWS(::napi_call_function(env, global, resolve, 0, nullptr, nullptr))
delete state;
return nullptr;
}
(*txnHandle)->state = TransactionState::Committing;
napi_value name;
NAPI_STATUS_THROWS(::napi_create_string_utf8(
env,
"transaction.commit",
NAPI_AUTO_LENGTH,
&name
))
NAPI_STATUS_THROWS(::napi_create_async_work(
env, // node_env
nullptr, // async_resource
name, // async_resource_name
[](napi_env env, void* data) { // execute
TransactionCommitState* state = reinterpret_cast<TransactionCommitState*>(data);
if (!state->handle || !state->handle->dbHandle || !state->handle->dbHandle->opened() || state->handle->dbHandle->isCancelled()) {
state->status = rocksdb::Status::Aborted("Database closed during transaction commit operation");
} else {
// set current timestamp before committing
auto now = std::chrono::system_clock::now();
auto timestamp = std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch()).count();
state->handle->txn->SetCommitTimestamp(timestamp);
state->status = state->handle->txn->Commit();
if (state->status.ok()) {
state->timestamp = timestamp;
DEBUG_LOG("Transaction::Commit emitted committed event\n")
state->handle->state = TransactionState::Committed;
state->handle->dbHandle->descriptor->notify(env, "committed", nullptr);
}
}
// signal that execute handler is complete
state->signalExecuteCompleted();
},
[](napi_env env, napi_status status, void* data) { // complete
TransactionCommitState* state = reinterpret_cast<TransactionCommitState*>(data);
// only process result if the work wasn't cancelled
if (status != napi_cancelled) {
napi_value global;
NAPI_STATUS_THROWS_VOID(::napi_get_global(env, &global))
if (state->status.ok()) {
DEBUG_LOG("Transaction::Commit complete closing handle=%p\n", state->handle.get())
if (state->handle) {
state->handle->close();
} else {
DEBUG_LOG("Transaction::Commit complete, but handle is null!\n")
}
napi_value result;
double milliseconds = static_cast<double>(state->timestamp) / 1000.0;
NAPI_STATUS_THROWS_VOID(::napi_create_double(env, milliseconds, &result))
DEBUG_LOG("Transaction::Commit complete calling resolve\n")
napi_value resolve;
NAPI_STATUS_THROWS_VOID(::napi_get_reference_value(env, state->resolveRef, &resolve))
NAPI_STATUS_THROWS_VOID(::napi_call_function(env, global, resolve, 1, &result, nullptr))
} else {
napi_value reject;
napi_value error;
NAPI_STATUS_THROWS_VOID(::napi_get_reference_value(env, state->rejectRef, &reject))
ROCKSDB_CREATE_ERROR_LIKE_VOID(error, state->status, "Transaction commit failed")
NAPI_STATUS_THROWS_VOID(::napi_call_function(env, global, reject, 1, &error, nullptr))
}
}
delete state;
},
state, // data
&state->asyncWork // -> result
));
// register the async work with the transaction handle
(*txnHandle)->registerAsyncWork();
NAPI_STATUS_THROWS(::napi_queue_async_work(env, state->asyncWork))
NAPI_RETURN_UNDEFINED()
}
/**
* Commits the transaction synchronously.
*/
napi_value Transaction::CommitSync(napi_env env, napi_callback_info info) {
NAPI_METHOD()
UNWRAP_TRANSACTION_HANDLE("CommitSync")
TransactionState txnState = (*txnHandle)->state;
if (txnState == TransactionState::Aborted) {
NAPI_THROW_JS_ERROR("ERR_ALREADY_ABORTED", "Transaction has already been aborted")
}
if (txnState == TransactionState::Committing || txnState == TransactionState::Committed) {
NAPI_RETURN_UNDEFINED()
}
(*txnHandle)->state = TransactionState::Committing;
// set current timestamp before committing
auto now = std::chrono::system_clock::now();
auto timestamp = std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch()).count();
(*txnHandle)->txn->SetCommitTimestamp(timestamp);
rocksdb::Status status = (*txnHandle)->txn->Commit();
if (status.ok()) {
DEBUG_LOG("Transaction::CommitSync emitted committed event\n")
(*txnHandle)->state = TransactionState::Committed;
(*txnHandle)->dbHandle->descriptor->notify(env, "committed", nullptr);
DEBUG_LOG("Transaction::CommitSync closing txnHandle=%p\n", (*txnHandle).get())
(*txnHandle)->close();
// Return the timestamp as milliseconds (convert from microseconds)
napi_value result;
double milliseconds = static_cast<double>(timestamp) / 1000.0;
NAPI_STATUS_THROWS(::napi_create_double(env, milliseconds, &result))
return result;
}
napi_value error;
ROCKSDB_CREATE_ERROR_LIKE_VOID(error, status, "Transaction commit failed")
NAPI_STATUS_THROWS(::napi_throw(env, error))
return nullptr;
}
/**
* Retrieves a value for the given key.
*/
napi_value Transaction::Get(napi_env env, napi_callback_info info) {
NAPI_METHOD_ARGV(3)
NAPI_GET_BUFFER(argv[0], key, "Key is required")
napi_value resolve = argv[1];
napi_value reject = argv[2];
UNWRAP_TRANSACTION_HANDLE("Get")
rocksdb::Slice keySlice(key + keyStart, keyEnd - keyStart);
return (*txnHandle)->get(env, keySlice, resolve, reject);
}
/**
* Gets the number of keys within a range or in the entire RocksDB database.
*
* @example
* ```ts
* const txn = new NativeTransaction(db);
* const total = txn.getCount();
* const range = txn.getCount({ start: 'a', end: 'z' });
* ```
*/
napi_value Transaction::GetCount(napi_env env, napi_callback_info info) {
NAPI_METHOD_ARGV(1)
UNWRAP_TRANSACTION_HANDLE("GetCount")
DBIteratorOptions itOptions;
itOptions.initFromNapiObject(env, argv[0]);
itOptions.values = false;
uint64_t count = 0;
(*txnHandle)->getCount(itOptions, count);
napi_value result;
NAPI_STATUS_THROWS(::napi_create_int64(env, count, &result))
return result;
}
/**
* Retrieves a value for the given key.
*/
napi_value Transaction::GetSync(napi_env env, napi_callback_info info) {
NAPI_METHOD_ARGV(1)
NAPI_GET_BUFFER(argv[0], key, "Key is required")
UNWRAP_TRANSACTION_HANDLE("GetSync")
rocksdb::Slice keySlice(key + keyStart, keyEnd - keyStart);
std::string value;
rocksdb::Status status = (*txnHandle)->getSync(keySlice, value);
if (status.IsNotFound()) {
NAPI_RETURN_UNDEFINED()
}
if (!status.ok()) {
::napi_throw_error(env, nullptr, status.ToString().c_str());
return nullptr;
}
napi_value result;
NAPI_STATUS_THROWS(::napi_create_buffer_copy(
env,
value.size(),
value.data(),
nullptr,
&result
))
return result;
}
/**
* Retrieves the ID of the transaction.
*/
napi_value Transaction::Id(napi_env env, napi_callback_info info) {
NAPI_METHOD()
UNWRAP_TRANSACTION_HANDLE("Id")
napi_value result;
NAPI_STATUS_THROWS(::napi_create_uint32(
env,
(*txnHandle)->id,
&result
))
return result;
}
/**
* Puts a value for the given key.
*/
napi_value Transaction::PutSync(napi_env env, napi_callback_info info) {
NAPI_METHOD_ARGV(2)
NAPI_GET_BUFFER(argv[0], key, "Key is required")
NAPI_GET_BUFFER(argv[1], value, nullptr)
UNWRAP_TRANSACTION_HANDLE("Put")
rocksdb::Slice keySlice(key + keyStart, keyEnd - keyStart);
rocksdb::Slice valueSlice(value + valueStart, valueEnd - valueStart);
DEBUG_LOG("%p Transaction::PutSync key:", txnHandle->get())
DEBUG_LOG_KEY_LN(keySlice)
DEBUG_LOG("%p Transaction::PutSync value:", txnHandle->get())
DEBUG_LOG_KEY_LN(valueSlice)
ROCKSDB_STATUS_THROWS_ERROR_LIKE((*txnHandle)->putSync(keySlice, valueSlice), "Transaction put failed")
NAPI_RETURN_UNDEFINED()
}
/**
* Removes a value for the given key.
*/
napi_value Transaction::RemoveSync(napi_env env, napi_callback_info info) {
NAPI_METHOD_ARGV(1)
NAPI_GET_BUFFER(argv[0], key, "Key is required")
UNWRAP_TRANSACTION_HANDLE("Remove")
rocksdb::Slice keySlice(key + keyStart, keyEnd - keyStart);
ROCKSDB_STATUS_THROWS_ERROR_LIKE((*txnHandle)->removeSync(keySlice), "Transaction remove failed")
NAPI_RETURN_UNDEFINED()
}
/**
* Initializes the `NativeTransaction` JavaScript class.
*/
void Transaction::Init(napi_env env, napi_value exports) {
napi_property_descriptor properties[] = {
{ "abort", nullptr, Abort, nullptr, nullptr, nullptr, napi_default, nullptr },
{ "commit", nullptr, Commit, nullptr, nullptr, nullptr, napi_default, nullptr },
{ "commitSync", nullptr, CommitSync, nullptr, nullptr, nullptr, napi_default, nullptr },
{ "get", nullptr, Get, nullptr, nullptr, nullptr, napi_default, nullptr },
{ "getCount", nullptr, GetCount, nullptr, nullptr, nullptr, napi_default, nullptr },
{ "getSync", nullptr, GetSync, nullptr, nullptr, nullptr, napi_default, nullptr },
{ "id", nullptr, nullptr, Id, nullptr, nullptr, napi_default, nullptr },
// merge?
{ "putSync", nullptr, PutSync, nullptr, nullptr, nullptr, napi_default, nullptr },
{ "removeSync", nullptr, RemoveSync, nullptr, nullptr, nullptr, napi_default, nullptr }
};
auto className = "Transaction";
constexpr size_t len = sizeof("Transaction") - 1;
napi_ref exportsRef;
NAPI_STATUS_THROWS_VOID(::napi_create_reference(env, exports, 1, &exportsRef))
napi_value ctor;
NAPI_STATUS_THROWS_VOID(::napi_define_class(
env,
className, // className
len, // length of class name
Constructor, // constructor
(void*)exportsRef, // constructor arg
sizeof(properties) / sizeof(napi_property_descriptor), // number of properties
properties, // properties array
&ctor // [out] constructor
))
NAPI_STATUS_THROWS_VOID(::napi_set_named_property(env, exports, className, ctor))
}
} // namespace rocksdb_js