forked from CoreyKaylor/Lightning.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLightningTransaction.cs
More file actions
519 lines (460 loc) · 21 KB
/
LightningTransaction.cs
File metadata and controls
519 lines (460 loc) · 21 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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
using System;
using static LightningDB.Native.Lmdb;
namespace LightningDB;
/// <summary>
/// Represents a transaction in the LightningDB environment.
/// Provides methods for managing database operations within the scope of a transaction, including
/// database access, key-value storage, and transaction control (commit, abort, etc.).
/// </summary>
/// <remarks>
/// A transaction and its cursors must only be used by a single thread, and a thread may only
/// have a single transaction at a time (except for read-only transactions when MDB_NOTLS is in use).
///
/// Transactions can be nested to any level. When a parent transaction has active child transactions,
/// it and its cursors may not issue any operations other than Commit and Abort.
///
/// Possible errors when creating transactions include:
/// - MDB_PANIC: A fatal error occurred earlier and the environment must be shut down
/// - MDB_MAP_RESIZED: Another process wrote data beyond this environment's mapsize and the map must be resized
/// - MDB_READERS_FULL: A read-only transaction was requested but the reader lock table is full
/// - ENOMEM: Out of memory
///
/// Cursors created within a transaction cannot span across transactions.
/// </remarks>
public sealed class LightningTransaction : IDisposable
{
/// <summary>
/// Default options used to begin new transactions.
/// </summary>
public const TransactionBeginFlags DefaultTransactionBeginFlags = TransactionBeginFlags.None;
internal nint _handle;
private readonly nint _originalHandle;
private bool _disposed;
/// <summary>
/// Created new instance of LightningTransaction
/// </summary>
/// <param name="environment">Environment.</param>
/// <param name="parent">Parent transaction or null.</param>
/// <param name="flags">Transaction open options.</param>
internal LightningTransaction(LightningEnvironment environment, LightningTransaction? parent, TransactionBeginFlags flags)
{
Environment = environment ?? throw new ArgumentNullException(nameof(environment));
ParentTransaction = parent;
IsReadOnly = flags == TransactionBeginFlags.ReadOnly;
State = LightningTransactionState.Ready;
var parentHandle = parent?._handle ?? default(nint);
mdb_txn_begin(environment._handle, parentHandle, flags, out _handle).ThrowOnError();
_originalHandle = _handle;
}
/// <summary>
/// Current transaction state.
/// </summary>
public LightningTransactionState State { get; private set; }
/// <summary>
/// Begin a child transaction.
/// </summary>
/// <param name="beginFlags">Options for a new transaction.</param>
/// <returns>New child transaction.</returns>
public LightningTransaction BeginTransaction(TransactionBeginFlags beginFlags = DefaultTransactionBeginFlags)
{
return new LightningTransaction(Environment, this, beginFlags);
}
/// <summary>
/// Opens the default (unnamed) database in context of this transaction with default configuration.
/// </summary>
/// <param name="closeOnDispose">Close database handle on dispose</param>
/// <returns>Created database wrapper.</returns>
public LightningDatabase OpenDatabase(bool closeOnDispose = false)
{
return OpenDatabaseImpl(null, new DatabaseConfiguration(), closeOnDispose);
}
/// <summary>
/// Opens the default (unnamed) database in context of this transaction.
/// </summary>
/// <param name="configuration">Database open options.</param>
/// <param name="closeOnDispose">Close database handle on dispose</param>
/// <returns>Created database wrapper.</returns>
public LightningDatabase OpenDatabase(DatabaseConfiguration configuration, bool closeOnDispose = false)
{
return OpenDatabaseImpl(null, configuration, closeOnDispose);
}
/// <summary>
/// Opens a named database in context of this transaction with default configuration.
/// </summary>
/// <param name="name">Database name.</param>
/// <param name="closeOnDispose">Close database handle on dispose</param>
/// <returns>Created database wrapper.</returns>
public LightningDatabase OpenDatabase(string name, bool closeOnDispose = false)
{
return OpenDatabaseImpl(name, new DatabaseConfiguration(), closeOnDispose);
}
/// <summary>
/// Opens a named database in context of this transaction.
/// </summary>
/// <param name="name">Database name.</param>
/// <param name="configuration">Database open options.</param>
/// <param name="closeOnDispose">Close database handle on dispose</param>
/// <returns>Created database wrapper.</returns>
public LightningDatabase OpenDatabase(string name, DatabaseConfiguration configuration, bool closeOnDispose = false)
{
return OpenDatabaseImpl(name, configuration, closeOnDispose);
}
private LightningDatabase OpenDatabaseImpl(string? name, DatabaseConfiguration configuration, bool closeOnDispose)
{
var db = new LightningDatabase(name, this, configuration, closeOnDispose);
return db;
}
/// <summary>
/// Drops the database.
/// </summary>
public MDBResultCode DropDatabase(LightningDatabase database)
{
return database.Drop(this);
}
/// <summary>
/// Truncates all data from the database.
/// </summary>
public MDBResultCode TruncateDatabase(LightningDatabase database)
{
return database.Truncate(this);
}
/// <summary>
/// Create a cursor.
/// Cursors are associated with a specific transaction and database and may not span threads.
/// </summary>
/// <param name="db">A database.</param>
public LightningCursor CreateCursor(LightningDatabase db)
{
return new LightningCursor(db, this);
}
/// <summary>
/// Get value from a database.
/// </summary>
/// <param name="db">The database to query.</param>
/// <param name="key">An array containing the key to look up.</param>
/// <returns>Requested value's byte array if exists, or null if not.</returns>
public (MDBResultCode resultCode, MDBValue key, MDBValue value) Get(LightningDatabase db, byte[] key)
{//argument validation delegated to next call
return Get(db, key.AsSpan());
}
/// <summary>
/// Get value from a database.
/// </summary>
/// <param name="db">The database to query.</param>
/// <param name="key">A span containing the key to look up.</param>
/// <returns>Requested value's byte array if exists, or null if not.</returns>
public unsafe (MDBResultCode resultCode, MDBValue key, MDBValue value) Get(LightningDatabase db, ReadOnlySpan<byte> key)
{
if (db == null)
throw new ArgumentNullException(nameof(db));
fixed(byte* keyBuffer = key)
{
var mdbKey = new MDBValue(key.Length, keyBuffer);
return (mdb_get(_handle, db._handle, ref mdbKey, out var mdbValue), mdbKey, mdbValue);
}
}
/// <summary>
/// Put data into a database.
/// </summary>
/// <param name="db">The database to query.</param>
/// <param name="key">A span containing the key to look up.</param>
/// <param name="value">A byte array containing the value found in the database, if it exists.</param>
/// <param name="options">Operation options (optional).</param>
public MDBResultCode Put(LightningDatabase db, byte[] key, byte[] value, PutOptions options = PutOptions.None)
{//argument validation delegated to next call
return Put(db, key.AsSpan(), value.AsSpan(), options);
}
/// <summary>
/// Put data into a database.
/// </summary>
/// <param name="db">Database.</param>
/// <param name="key">Key byte array.</param>
/// <param name="value">Value byte array.</param>
/// <param name="options">Operation options (optional).</param>
public unsafe MDBResultCode Put(LightningDatabase db, ReadOnlySpan<byte> key, ReadOnlySpan<byte> value, PutOptions options = PutOptions.None)
{
if (db == null)
throw new ArgumentNullException(nameof(db));
fixed (byte* keyPtr = key)
fixed (byte* valuePtr = value)
{
var mdbKey = new MDBValue(key.Length, keyPtr);
var mdbValue = new MDBValue(value.Length, valuePtr);
return mdb_put(_handle, db._handle, mdbKey, mdbValue, options);
}
}
/// <summary>
/// Delete items from a database.
/// This function removes key/data pairs from the database.
/// If the database does not support sorted duplicate data items (MDB_DUPSORT) the data parameter is ignored.
/// If the database supports sorted duplicates and the data parameter is NULL, all of the duplicate data items for the key will be deleted.
/// Otherwise, if the data parameter is non-NULL only the matching data item will be deleted.
/// This function will return MDB_NOTFOUND if the specified key/data pair is not in the database.
/// </summary>
/// <param name="db">A database handle returned by mdb_dbi_open()</param>
/// <param name="key">The key to delete from the database</param>
/// <param name="value">The data to delete (optional)</param>
public MDBResultCode Delete(LightningDatabase db, byte[] key, byte[] value)
{//argument validation delegated to next call
return Delete(db, key.AsSpan(), value.AsSpan());
}
/// <summary>
/// Delete items from a database.
/// This function removes key/data pairs from the database.
/// If the database does not support sorted duplicate data items (MDB_DUPSORT) the data parameter is ignored.
/// If the database supports sorted duplicates and the data parameter is NULL, all of the duplicate data items for the key will be deleted.
/// Otherwise, if the data parameter is non-NULL only the matching data item will be deleted.
/// This function will return MDB_NOTFOUND if the specified key/data pair is not in the database.
/// </summary>
/// <param name="db">A database handle returned by mdb_dbi_open()</param>
/// <param name="key">The key to delete from the database</param>
/// <param name="value">The data to delete (optional)</param>
public unsafe MDBResultCode Delete(LightningDatabase db, ReadOnlySpan<byte> key, ReadOnlySpan<byte> value)
{
if (db == null)
throw new ArgumentNullException(nameof(db));
fixed (byte* keyPtr = key)
fixed (byte* valuePtr = value)
{
var mdbKey = new MDBValue(key.Length, keyPtr);
if (value.IsEmpty)
{
return mdb_del(_handle, db._handle, mdbKey);
}
var mdbValue = new MDBValue(value.Length, valuePtr);
return mdb_del(_handle, db._handle, mdbKey, mdbValue);
}
}
/// <summary>
/// Delete items from a database.
/// This function removes key/data pairs from the database.
/// If the database does not support sorted duplicate data items (MDB_DUPSORT) the data parameter is ignored.
/// If the database supports sorted duplicates and the data parameter is NULL, all of the duplicate data items for the key will be deleted.
/// Otherwise, if the data parameter is non-NULL only the matching data item will be deleted.
/// This function will return MDB_NOTFOUND if the specified key/data pair is not in the database.
/// </summary>
/// <param name="db">A database handle returned by mdb_dbi_open()</param>
/// <param name="key">The key to delete from the database</param>
public MDBResultCode Delete(LightningDatabase db, byte[] key)
{
return Delete(db, key.AsSpan());
}
/// <summary>
/// Delete items from a database.
/// This function removes key/data pairs from the database.
/// If the database does not support sorted duplicate data items (MDB_DUPSORT) the data parameter is ignored.
/// If the database supports sorted duplicates and the data parameter is NULL, all of the duplicate data items for the key will be deleted.
/// Otherwise, if the data parameter is non-NULL only the matching data item will be deleted.
/// This function will return MDB_NOTFOUND if the specified key/data pair is not in the database.
/// </summary>
/// <param name="db">A database handle returned by mdb_dbi_open()</param>
/// <param name="key">The key to delete from the database</param>
public unsafe MDBResultCode Delete(LightningDatabase db, ReadOnlySpan<byte> key)
{
fixed(byte* ptr = key) {
var mdbKey = new MDBValue(key.Length, ptr);
return mdb_del(_handle, db._handle, mdbKey);
}
}
/// <summary>
/// Aborts the read-only transaction and resets the transaction handle so it can be
/// reused after calling <see cref="Renew"/>
/// </summary>
/// <remarks>
/// Resetting a transaction releases any internal locks or resources associated with it without
/// completely destroying the transaction object. This is more efficient than creating a new
/// transaction when you need to perform another read operation after completing one.
///
/// After calling Reset, you must call <see cref="Renew"/> before using the transaction again.
///
/// This method can only be called on read-only transactions. For read-write transactions,
/// you must use <see cref="Commit"/> or <see cref="Abort"/>.
///
/// This method also releases the reader slot in the lock table, allowing it to be
/// reused immediately instead of waiting for the environment to close or the thread to terminate.
/// </remarks>
public void Reset()
{
if (!IsReadOnly)
throw new InvalidOperationException("Can't reset non-readonly transaction");
if(State != LightningTransactionState.Ready && State != LightningTransactionState.Done)
throw new InvalidOperationException("Transaction has already been reset");
State = LightningTransactionState.Reset;
mdb_txn_reset(_handle);
}
/// <summary>
/// Renews a read-only transaction previously released with <see cref="Reset"/>
/// </summary>
/// <remarks>
/// This function refreshes the transaction handle and makes it available for reuse.
/// It must be called before reusing a read-only transaction that was reset with <see cref="Reset"/>.
///
/// Renewing a transaction is much more efficient than creating a new transaction, as it
/// reuses the same transaction handle and reader slot.
///
/// This function can only be used on read-only transactions that have been reset.
///
/// After a successful call to Renew, the transaction will be in the Ready state and
/// can be used for database operations again.
/// </remarks>
public MDBResultCode Renew()
{
if (!IsReadOnly)
throw new InvalidOperationException("Can't renew non-readonly transaction");
if (State != LightningTransactionState.Reset)
throw new InvalidOperationException("Transaction should be reset first");
State = LightningTransactionState.Done;
var result = mdb_txn_renew(_handle).ThrowOnError();
State = LightningTransactionState.Ready;
return result;
}
/// <summary>
/// Commit all the operations of a transaction into the database.
/// </summary>
public MDBResultCode Commit()
{
if(State != LightningTransactionState.Ready)
throw new InvalidOperationException("Transaction that is not ready cannot be committed");
if (ParentTransaction != null && ParentTransaction.State != LightningTransactionState.Ready)
{
State = ParentTransaction.State;
return MDBResultCode.BadTxn;
}
State = LightningTransactionState.Done;
return mdb_txn_commit(_handle);
}
/// <summary>
/// Abandon all the operations of the transaction instead of saving them.
/// </summary>
public void Abort()
{
if(State != LightningTransactionState.Ready)
throw new InvalidOperationException("Transaction that is not ready cannot be committed");
State = LightningTransactionState.Done;
mdb_txn_abort(_handle);
}
/// <summary>
/// The number of items in the database.
/// </summary>
/// <param name="db">The database we are counting items in.</param>
/// <returns>The number of items.</returns>
public long GetEntriesCount(LightningDatabase db)
{
mdb_stat(_handle, db._handle, out var stat).ThrowOnError();
return stat.ms_entries;
}
/// <summary>
/// Retrieve the statistics for the specified database.
/// </summary>
/// <param name="db">The database we are interested in.</param>
/// <returns>The retrieved statistics.</returns>
public Stats GetStats(LightningDatabase db)
{
mdb_stat(_handle, db._handle, out var stat).ThrowOnError();
return new Stats
{
BranchPages = stat.ms_branch_pages,
BTreeDepth = stat.ms_depth,
Entries = stat.ms_entries,
LeafPages = stat.ms_leaf_pages,
OverflowPages = stat.ms_overflow_pages,
PageSize = stat.ms_psize
};
}
/// <summary>
/// Environment in which the transaction was opened.
/// </summary>
public LightningEnvironment Environment { get; }
/// <summary>
/// Parent transaction of this transaction.
/// </summary>
public LightningTransaction? ParentTransaction { get; }
/// <summary>
/// Whether this transaction is read-only.
/// </summary>
public bool IsReadOnly { get; }
/// <summary>
/// Gets the transaction ID.
/// </summary>
public nuint Id => mdb_txn_id(_handle);
/// <summary>
/// Compares two data items according to the database's key comparison function.
/// </summary>
/// <param name="db">The database to use for comparison</param>
/// <param name="a">First item to compare</param>
/// <param name="b">Second item to compare</param>
/// <returns>Negative value if a is less than b, zero if equal, positive if a is greater than b</returns>
public unsafe int CompareKeys(LightningDatabase db, ReadOnlySpan<byte> a, ReadOnlySpan<byte> b)
{
if (db == null)
throw new ArgumentNullException(nameof(db));
fixed (byte* aPtr = a)
fixed (byte* bPtr = b)
{
var mdbA = new MDBValue(a.Length, aPtr);
var mdbB = new MDBValue(b.Length, bPtr);
return mdb_cmp(_handle, db._handle, ref mdbA, ref mdbB);
}
}
/// <summary>
/// Compares two data items according to the database's data comparison function.
/// </summary>
/// <param name="db">The database to use for comparison</param>
/// <param name="a">First item to compare</param>
/// <param name="b">Second item to compare</param>
/// <returns>Negative value if a is less than b, zero if equal, positive if a is greater than b</returns>
public unsafe int CompareData(LightningDatabase db, ReadOnlySpan<byte> a, ReadOnlySpan<byte> b)
{
if (db == null)
throw new ArgumentNullException(nameof(db));
fixed (byte* aPtr = a)
fixed (byte* bPtr = b)
{
var mdbA = new MDBValue(a.Length, aPtr);
var mdbB = new MDBValue(b.Length, bPtr);
return mdb_dcmp(_handle, db._handle, ref mdbA, ref mdbB);
}
}
/// <summary>
/// Dispose this transaction and deallocate all resources associated with it.
/// </summary>
/// <param name="disposing">True if called from Dispose.</param>
private void Dispose(bool disposing)
{
if (_disposed)
return;
_disposed = true;
if (!Environment.IsOpened)
throw new InvalidOperationException("A transaction must be disposed before closing the environment");
if (State == LightningTransactionState.Ready && Environment.IsOpened)
{
Abort();
}
State = LightningTransactionState.Released;
_handle = default;
if (disposing)
{
GC.SuppressFinalize(this);
}
}
/// <summary>
/// Dispose this transaction and deallocate all resources associated with it.
/// </summary>
public void Dispose()
{
Dispose(true);
}
~LightningTransaction()
{
Dispose(false);
}
public override int GetHashCode()
{
return _originalHandle.GetHashCode();
}
public override bool Equals(object? obj)
{
var tran = obj as LightningTransaction;
return tran != null && _handle.Equals(tran._handle);
}
}