forked from mongodb/mongo-csharp-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCoreSession.cs
More file actions
636 lines (549 loc) · 24.8 KB
/
CoreSession.cs
File metadata and controls
636 lines (549 loc) · 24.8 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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
/* Copyright 2010-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver.Core.Clusters;
using MongoDB.Driver.Core.Misc;
using MongoDB.Driver.Core.Operations;
using MongoDB.Driver.Core.Servers;
namespace MongoDB.Driver.Core.Bindings
{
/// <summary>
/// Represents a session.
/// </summary>
/// <seealso cref="MongoDB.Driver.Core.Bindings.ICoreSession" />
public sealed class CoreSession : ICoreSession, ICoreSessionInternal
{
// private fields
#pragma warning disable CA2213 // Disposable fields should be disposed
private readonly IClusterInternal _cluster;
#pragma warning restore CA2213 // Disposable fields should be disposed
private readonly IClusterClock _clusterClock = new ClusterClock();
private CoreTransaction _currentTransaction;
private bool _disposed;
private bool _isCommitTransactionInProgress;
private readonly IOperationClock _operationClock = new OperationClock();
private readonly CoreSessionOptions _options;
private readonly Lazy<ICoreServerSession> _serverSession;
private BsonTimestamp _snapshotTime;
// constructors
internal CoreSession(
IClusterInternal cluster,
ICoreServerSession serverSession,
CoreSessionOptions options)
: this(cluster, options: options)
{
Ensure.IsNotNull(serverSession, nameof(serverSession));
_serverSession = new Lazy<ICoreServerSession>(() => serverSession);
}
internal CoreSession(
IClusterInternal cluster,
ICoreServerSessionPool serverSessionPool,
CoreSessionOptions options)
: this(cluster, options)
{
Ensure.IsNotNull(serverSessionPool, nameof(serverSessionPool));
_serverSession = new Lazy<ICoreServerSession>(() => serverSessionPool.AcquireSession());
}
private CoreSession(
IClusterInternal cluster,
CoreSessionOptions options)
{
_cluster = Ensure.IsNotNull(cluster, nameof(cluster));
_options = Ensure.IsNotNull(options, nameof(options));
_snapshotTime = options.SnapshotTime;
}
// public properties
/// <summary>
/// Gets the cluster.
/// </summary>
/// <value>
/// The cluster.
/// </value>
public ICluster Cluster => _cluster;
/// <inheritdoc />
public BsonDocument ClusterTime => _clusterClock.ClusterTime;
/// <inheritdoc />
public CoreTransaction CurrentTransaction => _currentTransaction;
/// <inheritdoc />
public BsonDocument Id => _serverSession.Value.Id;
/// <inheritdoc />
public bool IsCausallyConsistent => _options.IsCausallyConsistent;
/// <inheritdoc />
public bool IsDirty => _serverSession.Value.IsDirty;
/// <inheritdoc />
public bool IsImplicit => _options.IsImplicit;
/// <inheritdoc />
public bool IsInTransaction
{
get
{
if (_currentTransaction != null)
{
switch (_currentTransaction.State)
{
case CoreTransactionState.Aborted:
return false;
case CoreTransactionState.Committed:
return _isCommitTransactionInProgress; // when retrying a commit we are temporarily "back in" the already committed transaction
default:
return true;
}
}
return false;
}
}
/// <inheritdoc />
public bool IsSnapshot => _options.IsSnapshot;
/// <inheritdoc />
public BsonTimestamp OperationTime => _operationClock.OperationTime;
/// <inheritdoc />
public CoreSessionOptions Options => _options;
/// <inheritdoc />
public ICoreServerSession ServerSession => _serverSession.Value;
/// <inheritdoc />
public BsonTimestamp SnapshotTime => _snapshotTime;
// public methods
/// <inheritdoc />
public void AbortTransaction(CancellationToken cancellationToken = default)
=> ((ICoreSessionInternal)this).AbortTransaction(null, cancellationToken);
// TODO: CSOT: Make it public when CSOT will be ready for GA and add default value to cancellationToken parameter.
void ICoreSessionInternal.AbortTransaction(AbortTransactionOptions options, CancellationToken cancellationToken)
{
EnsureAbortTransactionCanBeCalled(nameof(AbortTransaction));
using var operationContext = new OperationContext(GetTimeout(options?.Timeout), cancellationToken);
try
{
if (_currentTransaction.IsEmpty)
{
return;
}
try
{
var firstAttempt = CreateAbortTransactionOperation(operationContext);
ExecuteEndTransactionOnPrimary(operationContext, firstAttempt);
return;
}
catch (Exception exception) when (ShouldRetryEndTransactionException(operationContext, exception))
{
// unpin if retryable error
_currentTransaction.UnpinAll();
// ignore exception and retry
}
catch
{
return; // ignore exception and return
}
try
{
var secondAttempt = CreateAbortTransactionOperation(operationContext);
ExecuteEndTransactionOnPrimary(operationContext, secondAttempt);
}
catch
{
return; // ignore exception and return
}
}
finally
{
_currentTransaction.SetState(CoreTransactionState.Aborted);
// The transaction is aborted.The session MUST be unpinned regardless
// of whether the abortTransaction command succeeds or fails
_currentTransaction.UnpinAll();
}
}
/// <inheritdoc />
public Task AbortTransactionAsync(CancellationToken cancellationToken = default)
=> ((ICoreSessionInternal)this).AbortTransactionAsync(null, cancellationToken);
// TODO: CSOT: Make it public when CSOT will be ready for GA and add default value to cancellationToken parameter.
async Task ICoreSessionInternal.AbortTransactionAsync(AbortTransactionOptions options, CancellationToken cancellationToken)
{
EnsureAbortTransactionCanBeCalled(nameof(AbortTransaction));
using var operationContext = new OperationContext(GetTimeout(options?.Timeout), cancellationToken);
try
{
if (_currentTransaction.IsEmpty)
{
return;
}
try
{
var firstAttempt = CreateAbortTransactionOperation(operationContext);
await ExecuteEndTransactionOnPrimaryAsync(operationContext, firstAttempt).ConfigureAwait(false);
return;
}
catch (Exception exception) when (ShouldRetryEndTransactionException(operationContext, exception))
{
// unpin if retryable error
_currentTransaction.UnpinAll();
// ignore exception and retry
}
catch
{
return; // ignore exception and return
}
try
{
var secondAttempt = CreateAbortTransactionOperation(operationContext);
await ExecuteEndTransactionOnPrimaryAsync(operationContext, secondAttempt).ConfigureAwait(false);
}
catch
{
return; // ignore exception and return
}
}
finally
{
_currentTransaction.SetState(CoreTransactionState.Aborted);
// The transaction is aborted.The session MUST be unpinned regardless
// of whether the abortTransaction command succeeds or fails
_currentTransaction.UnpinAll();
}
}
/// <inheritdoc />
public void AboutToSendCommand()
{
if (_currentTransaction != null)
{
switch (_currentTransaction.State)
{
case CoreTransactionState.Starting: // Starting changes to InProgress after the message is sent to the server
case CoreTransactionState.InProgress:
return;
case CoreTransactionState.Aborted:
_currentTransaction = null;
break;
case CoreTransactionState.Committed:
// don't set to null when retrying a commit
if (!_isCommitTransactionInProgress)
{
// Unpin data non-transaction operation uses the commited session
_currentTransaction.UnpinAll();
_currentTransaction = null;
}
return;
default:
throw new Exception($"Unexpected transaction state: {_currentTransaction.State}.");
}
}
}
/// <inheritdoc />
public void AdvanceClusterTime(BsonDocument newClusterTime)
{
_clusterClock.AdvanceClusterTime(newClusterTime);
}
/// <inheritdoc />
public void AdvanceOperationTime(BsonTimestamp newOperationTime)
{
_operationClock.AdvanceOperationTime(newOperationTime);
}
/// <inheritdoc />
public long AdvanceTransactionNumber()
{
return _serverSession.Value.AdvanceTransactionNumber();
}
/// <inheritdoc />
public void CommitTransaction(CancellationToken cancellationToken = default)
=> ((ICoreSessionInternal)this).CommitTransaction(null, cancellationToken);
// TODO: CSOT: Make it public when CSOT will be ready for GA and add default value to cancellationToken parameter.
void ICoreSessionInternal.CommitTransaction(CommitTransactionOptions options, CancellationToken cancellationToken)
{
EnsureCommitTransactionCanBeCalled(nameof(CommitTransaction));
using var operationContext = new OperationContext(GetTimeout(options?.Timeout), cancellationToken);
try
{
_isCommitTransactionInProgress = true;
if (_currentTransaction.IsEmpty)
{
return;
}
try
{
var firstAttempt = CreateCommitTransactionOperation(operationContext, IsFirstCommitAttemptRetry());
ExecuteEndTransactionOnPrimary(operationContext, firstAttempt);
return;
}
catch (Exception exception) when (ShouldRetryEndTransactionException(operationContext, exception))
{
// unpin server if needed, then ignore exception and retry
TransactionHelper.UnpinServerIfNeededOnRetryableCommitException(_currentTransaction, exception);
}
var secondAttempt = CreateCommitTransactionOperation(operationContext, isCommitRetry: true);
ExecuteEndTransactionOnPrimary(operationContext, secondAttempt);
}
finally
{
_isCommitTransactionInProgress = false;
_currentTransaction.SetState(CoreTransactionState.Committed);
}
}
/// <inheritdoc />
public Task CommitTransactionAsync(CancellationToken cancellationToken = default)
=> ((ICoreSessionInternal)this).CommitTransactionAsync(null, cancellationToken);
// TODO: CSOT: Make it public when CSOT will be ready for GA and add default value to cancellationToken parameter.
async Task ICoreSessionInternal.CommitTransactionAsync(CommitTransactionOptions options, CancellationToken cancellationToken)
{
EnsureCommitTransactionCanBeCalled(nameof(CommitTransaction));
using var operationContext = new OperationContext(GetTimeout(options?.Timeout), cancellationToken);
try
{
_isCommitTransactionInProgress = true;
if (_currentTransaction.IsEmpty)
{
return;
}
try
{
var firstAttempt = CreateCommitTransactionOperation(operationContext, IsFirstCommitAttemptRetry());
await ExecuteEndTransactionOnPrimaryAsync(operationContext, firstAttempt).ConfigureAwait(false);
return;
}
catch (Exception exception) when (ShouldRetryEndTransactionException(operationContext, exception))
{
// unpin server if needed, then ignore exception and retry
TransactionHelper.UnpinServerIfNeededOnRetryableCommitException(_currentTransaction, exception);
}
var secondAttempt = CreateCommitTransactionOperation(operationContext, isCommitRetry: true);
await ExecuteEndTransactionOnPrimaryAsync(operationContext, secondAttempt).ConfigureAwait(false);
}
finally
{
_isCommitTransactionInProgress = false;
_currentTransaction.SetState(CoreTransactionState.Committed);
}
}
/// <inheritdoc />
public void Dispose()
{
if (!_disposed)
{
if (_currentTransaction != null)
{
switch (_currentTransaction.State)
{
case CoreTransactionState.Starting:
case CoreTransactionState.InProgress:
try
{
AbortTransaction(CancellationToken.None);
}
catch
{
// ignore exceptions
}
break;
}
}
_currentTransaction?.UnpinAll();
_serverSession.Value.Dispose();
_disposed = true;
}
}
/// <inheritdoc />
public void MarkDirty()
{
_serverSession.Value.MarkDirty();
}
/// <inheritdoc />
public void StartTransaction(TransactionOptions transactionOptions = null)
{
EnsureStartTransactionCanBeCalled();
var transactionNumber = AdvanceTransactionNumber();
var effectiveTransactionOptions = GetEffectiveTransactionOptions(transactionOptions);
if (!effectiveTransactionOptions.WriteConcern.IsAcknowledged)
{
throw new InvalidOperationException("Transactions do not support unacknowledged write concerns.");
}
_currentTransaction?.UnpinAll(); // unpin data if any when a new transaction is started
_currentTransaction = new CoreTransaction(transactionNumber, effectiveTransactionOptions);
}
/// <inheritdoc />
public void SetSnapshotTimeIfNeeded(BsonTimestamp snapshotTime)
{
if (IsSnapshot && _snapshotTime == null)
{
_snapshotTime = snapshotTime;
}
}
/// <inheritdoc />
public void WasUsed()
{
_serverSession.Value.WasUsed();
}
// private methods
private IReadOperation<BsonDocument> CreateAbortTransactionOperation(OperationContext operationContext)
{
return new AbortTransactionOperation(_currentTransaction.RecoveryToken, GetTransactionWriteConcern(operationContext));
}
private IReadOperation<BsonDocument> CreateCommitTransactionOperation(OperationContext operationContext, bool isCommitRetry)
{
var writeConcern = GetCommitTransactionWriteConcern(operationContext, isCommitRetry);
var maxCommitTime = _currentTransaction.TransactionOptions.MaxCommitTime;
return new CommitTransactionOperation(_currentTransaction.RecoveryToken, writeConcern) { MaxCommitTime = maxCommitTime };
}
private void EnsureAbortTransactionCanBeCalled(string methodName)
{
if (_currentTransaction == null)
{
throw new InvalidOperationException($"{methodName} cannot be called when no transaction started.");
}
switch (_currentTransaction.State)
{
case CoreTransactionState.Starting:
case CoreTransactionState.InProgress:
return;
case CoreTransactionState.Aborted:
throw new InvalidOperationException($"Cannot call {methodName} twice.");
case CoreTransactionState.Committed:
throw new InvalidOperationException($"Cannot call {methodName} after calling CommitTransaction.");
default:
throw new Exception($"{methodName} called in unexpected transaction state: {_currentTransaction.State}.");
}
}
private void EnsureCommitTransactionCanBeCalled(string methodName)
{
if (_currentTransaction == null)
{
throw new InvalidOperationException($"{methodName} cannot be called when no transaction started.");
}
switch (_currentTransaction.State)
{
case CoreTransactionState.Starting:
case CoreTransactionState.InProgress:
case CoreTransactionState.Committed:
return;
case CoreTransactionState.Aborted:
throw new InvalidOperationException($"Cannot call {methodName} after calling AbortTransaction.");
default:
throw new Exception($"{methodName} called in unexpected transaction state: {_currentTransaction.State}.");
}
}
private void EnsureStartTransactionCanBeCalled()
{
if (IsSnapshot)
{
throw new MongoClientException("Transactions are not supported in snapshot sessions.");
}
if (_currentTransaction == null)
{
EnsureTransactionsAreSupported();
}
else
{
switch (_currentTransaction.State)
{
case CoreTransactionState.Aborted:
case CoreTransactionState.Committed:
break;
default:
throw new InvalidOperationException("Transaction already in progress.");
}
}
}
private void EnsureTransactionsAreSupported()
{
if (_cluster.Description.Type == ClusterType.LoadBalanced)
{
// LB always supports transactions
return;
}
var connectedDataBearingServers = _cluster.Description.Servers.Where(s => s.State == ServerState.Connected && s.IsDataBearing).ToList();
foreach (var connectedDataBearingServer in connectedDataBearingServers)
{
var serverType = connectedDataBearingServer.Type;
switch (serverType)
{
case ServerType.Standalone:
throw new NotSupportedException("Standalone servers do not support transactions.");
case ServerType.ShardRouter:
Feature.ShardedTransactions.ThrowIfNotSupported(connectedDataBearingServer.MaxWireVersion);
break;
case ServerType.LoadBalanced:
// do nothing, load balancing always supports transactions
break;
default:
Feature.Transactions.ThrowIfNotSupported(connectedDataBearingServer.MaxWireVersion);
break;
}
}
}
private TResult ExecuteEndTransactionOnPrimary<TResult>(OperationContext operationContext, IReadOperation<TResult> operation)
{
using (var sessionHandle = new NonDisposingCoreSessionHandle(this))
using (var binding = ChannelPinningHelper.CreateReadWriteBinding(_cluster, sessionHandle))
{
return operation.Execute(operationContext, binding);
}
}
private async Task<TResult> ExecuteEndTransactionOnPrimaryAsync<TResult>(OperationContext operationContext, IReadOperation<TResult> operation)
{
using (var sessionHandle = new NonDisposingCoreSessionHandle(this))
using (var binding = ChannelPinningHelper.CreateReadWriteBinding(_cluster, sessionHandle))
{
return await operation.ExecuteAsync(operationContext, binding).ConfigureAwait(false);
}
}
private TimeSpan? GetTimeout(TimeSpan? timeout)
=> timeout ?? _options.DefaultTransactionOptions?.Timeout;
private TransactionOptions GetEffectiveTransactionOptions(TransactionOptions transactionOptions)
{
var readConcern = transactionOptions?.ReadConcern ?? _options.DefaultTransactionOptions?.ReadConcern ?? ReadConcern.Default;
var readPreference = transactionOptions?.ReadPreference ?? _options.DefaultTransactionOptions?.ReadPreference ?? ReadPreference.Primary;
var writeConcern = transactionOptions?.WriteConcern ?? _options.DefaultTransactionOptions?.WriteConcern ?? new WriteConcern();
var maxCommitTime = transactionOptions?.MaxCommitTime ?? _options.DefaultTransactionOptions?.MaxCommitTime;
return new TransactionOptions(readConcern, readPreference, writeConcern, maxCommitTime);
}
private WriteConcern GetTransactionWriteConcern(OperationContext operationContext)
{
var writeConcern = _currentTransaction.TransactionOptions?.WriteConcern ??
_options.DefaultTransactionOptions?.WriteConcern ??
WriteConcern.WMajority;
if (operationContext.IsRootContextTimeoutConfigured())
{
writeConcern = writeConcern.With(wTimeout: null);
}
return writeConcern;
}
private WriteConcern GetCommitTransactionWriteConcern(OperationContext operationContext, bool isCommitRetry)
{
var writeConcern = GetTransactionWriteConcern(operationContext);
if (isCommitRetry)
{
writeConcern = writeConcern.With(mode: "majority");
if (writeConcern.WTimeout == null && !operationContext.IsRootContextTimeoutConfigured())
{
writeConcern = writeConcern.With(wTimeout: TimeSpan.FromMilliseconds(10000));
}
}
return writeConcern;
}
private bool IsFirstCommitAttemptRetry()
{
// According to the spec, trying to commit again while the state is "committed" is considered a retry.
return _currentTransaction.State == CoreTransactionState.Committed;
}
private bool ShouldRetryEndTransactionException(OperationContext operationContext, Exception exception)
{
if (!RetryabilityHelper.IsRetryableWriteException(exception))
{
return false;
}
return operationContext.IsRootContextTimeoutConfigured() ? !operationContext.IsTimedOut() : true;
}
}
}