forked from dotnet/orleans
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTransactionAttribute.cs
485 lines (415 loc) · 17 KB
/
TransactionAttribute.cs
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
using System;
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Orleans.CodeGeneration;
using Orleans.Runtime;
using Orleans.Serialization;
using Orleans.Serialization.Invocation;
using Orleans.Transactions;
namespace Orleans
{
/// <summary>
/// The TransactionAttribute attribute is used to mark methods that start and join transactions.
/// </summary>
[InvokableCustomInitializer("SetTransactionOptions")]
[InvokableBaseType(typeof(GrainReference), typeof(ValueTask), typeof(TransactionRequest))]
[InvokableBaseType(typeof(GrainReference), typeof(ValueTask<>), typeof(TransactionRequest<>))]
[InvokableBaseType(typeof(GrainReference), typeof(Task), typeof(TransactionTaskRequest))]
[InvokableBaseType(typeof(GrainReference), typeof(Task<>), typeof(TransactionTaskRequest<>))]
[AttributeUsage(AttributeTargets.Method)]
public sealed class TransactionAttribute : Attribute
{
public TransactionAttribute(TransactionOption requirement)
{
Requirement = requirement;
ReadOnly = false;
}
public TransactionAttribute(TransactionOptionAlias alias)
{
Requirement = (TransactionOption)(int)alias;
ReadOnly = false;
}
public TransactionOption Requirement { get; }
public bool ReadOnly { get; set; }
}
public enum TransactionOption
{
Suppress, // Logic is not transactional but can be called from within a transaction. If called within the context of a transaction, the context will not be passed to the call.
CreateOrJoin, // Logic is transactional. If called within the context of a transaction, it will use that context, else it will create a new context.
Create, // Logic is transactional and will always create a new transaction context, even if called within an existing transaction context.
Join, // Logic is transactional but can only be called within the context of an existing transaction.
Supported, // Logic is not transactional but supports transactions. If called within the context of a transaction, the context will be passed to the call.
NotAllowed // Logic is not transactional and cannot be called from within a transaction. If called within the context of a transaction, it will throw a not supported exception.
}
public enum TransactionOptionAlias
{
Suppress = TransactionOption.Supported,
Required = TransactionOption.CreateOrJoin,
RequiresNew = TransactionOption.Create,
Mandatory = TransactionOption.Join,
Never = TransactionOption.NotAllowed,
}
[GenerateSerializer]
public abstract class TransactionRequestBase : RequestBase, IOutgoingGrainCallFilter, IOnDeserialized
{
[NonSerialized]
private Serializer<OrleansTransactionAbortedException> _serializer;
[NonSerialized]
private ITransactionAgent _transactionAgent;
private ITransactionAgent TransactionAgent => _transactionAgent ?? throw new OrleansTransactionsDisabledException();
[Id(0)]
public TransactionOption TransactionOption { get; set; }
[Id(1)]
public TransactionInfo TransactionInfo { get; set; }
[GeneratedActivatorConstructor]
protected TransactionRequestBase(Serializer<OrleansTransactionAbortedException> exceptionSerializer, IServiceProvider serviceProvider)
{
_serializer = exceptionSerializer;
// May be null, eg on an external client. We will throw if it's null at the time of invocation.
_transactionAgent = serviceProvider.GetService<ITransactionAgent>();
}
public bool IsAmbientTransactionSuppressed => TransactionOption switch
{
TransactionOption.Create => true,
TransactionOption.Suppress => true,
_ => false
};
public bool IsTransactionRequired => TransactionOption switch
{
TransactionOption.Create => true,
TransactionOption.CreateOrJoin => true,
TransactionOption.Join => true,
_ => false
};
protected void SetTransactionOptions(TransactionOptionAlias txOption) => SetTransactionOptions((TransactionOption)txOption);
protected void SetTransactionOptions(TransactionOption txOption)
{
this.TransactionOption = txOption;
}
async Task IOutgoingGrainCallFilter.Invoke(IOutgoingGrainCallContext context)
{
var transactionInfo = SetTransactionInfo();
try
{
await context.Invoke();
}
finally
{
if (context.Response is TransactionResponse txResponse)
{
var returnedTransactionInfo = txResponse.TransactionInfo;
if (transactionInfo is { } && returnedTransactionInfo is { })
{
transactionInfo.Join(returnedTransactionInfo);
}
if (txResponse.GetException() is { } exception)
{
ExceptionDispatchInfo.Throw(exception);
}
}
}
}
private TransactionInfo SetTransactionInfo()
{
// Clear transaction info if transaction operation requires new transaction.
var transactionInfo = TransactionContext.GetTransactionInfo();
// Enforce join transaction calls
if (TransactionOption == TransactionOption.Join && transactionInfo == null)
{
throw new NotSupportedException("Call cannot be made outside of a transaction.");
}
// Enforce not allowed transaction calls
if (TransactionOption == TransactionOption.NotAllowed && transactionInfo != null)
{
throw new NotSupportedException("Call cannot be made within a transaction.");
}
// Clear transaction context if creating a transaction or transaction is suppressed
if (TransactionOption is TransactionOption.Create or TransactionOption.Suppress)
{
transactionInfo = null;
}
if (transactionInfo == null)
{
// if we're leaving a transaction context, make sure it's been cleared from the request context.
TransactionContext.Clear();
}
else
{
this.TransactionInfo = transactionInfo?.Fork();
}
return transactionInfo;
}
public override async ValueTask<Response> Invoke()
{
Response response;
var transactionInfo = this.TransactionInfo;
bool startedNewTransaction = false;
try
{
if (IsTransactionRequired && transactionInfo == null)
{
// TODO: this should be a configurable parameter
var transactionTimeout = Debugger.IsAttached ? TimeSpan.FromMinutes(30) : TimeSpan.FromSeconds(10);
// Start a new transaction
var isReadOnly = (this.Options | InvokeMethodOptions.ReadOnly) == InvokeMethodOptions.ReadOnly;
transactionInfo = await TransactionAgent.StartTransaction(isReadOnly, transactionTimeout);
startedNewTransaction = true;
}
TransactionContext.SetTransactionInfo(transactionInfo);
response = await BaseInvoke();
}
catch (Exception exception)
{
response = Response.FromException(exception);
}
finally
{
TransactionContext.Clear();
}
if (transactionInfo != null)
{
transactionInfo.ReconcilePending();
if (response.Exception is { } invokeException)
{
// Record reason for abort, if not already set.
transactionInfo.RecordException(invokeException, _serializer);
}
OrleansTransactionException transactionException = transactionInfo.MustAbort(_serializer);
// This request started the transaction, so we try to commit before returning,
// or if it must abort, tell participants that it aborted
if (startedNewTransaction)
{
if (transactionException is not null || transactionInfo.TryToCommit is false)
{
await TransactionAgent.Abort(transactionInfo);
}
else
{
var (status, exception) = await TransactionAgent.Resolve(transactionInfo);
if (status != TransactionalStatus.Ok)
{
transactionException = status.ConvertToUserException(transactionInfo.Id, exception);
}
}
}
if (transactionException != null)
{
response = Response.FromException(transactionException);
}
response = TransactionResponse.Create(response, transactionInfo);
}
return response;
}
protected abstract ValueTask<Response> BaseInvoke();
public override void Dispose()
{
TransactionInfo = null;
}
void IOnDeserialized.OnDeserialized(DeserializationContext context)
{
_serializer = context.ServiceProvider.GetRequiredService<Serializer<OrleansTransactionAbortedException>>();
_transactionAgent = context.ServiceProvider.GetRequiredService<ITransactionAgent>();
}
}
[GenerateSerializer]
public sealed class TransactionResponse : Response
{
[Id(0)]
private Response _response;
[Id(1)]
public TransactionInfo TransactionInfo { get; set; }
public static TransactionResponse Create(Response response, TransactionInfo transactionInfo)
{
return new TransactionResponse
{
_response = response,
TransactionInfo = transactionInfo
};
}
public Response InnerResponse => _response;
public override object Result
{
get
{
if (_response.Exception is { } exception)
{
ExceptionDispatchInfo.Capture(exception).Throw();
}
return _response.Result;
}
set => _response.Result = value;
}
public override Exception Exception
{
get
{
// Suppress any exception here, allowing ResponseCompletionSource to complete with a Response instead of an exception.
// This gives TransactionRequestBase a chance to inspect this instance and retrieve the TransactionInfo property first.
// After, it will use GetException to get and throw the exeption.
return null;
}
set => _response.Exception = value;
}
public Exception GetException() => _response.Exception;
public override void Dispose()
{
TransactionInfo = null;
_response.Dispose();
}
public override T GetResult<T>() => _response.GetResult<T>();
}
[SerializerTransparent]
public abstract class TransactionRequest : TransactionRequestBase
{
protected TransactionRequest(Serializer<OrleansTransactionAbortedException> exceptionSerializer, IServiceProvider serviceProvider) : base(exceptionSerializer, serviceProvider)
{
}
protected sealed override ValueTask<Response> BaseInvoke()
{
try
{
var resultTask = InvokeInner();
if (resultTask.IsCompleted)
{
resultTask.GetAwaiter().GetResult();
return new ValueTask<Response>(Response.Completed);
}
return CompleteInvokeAsync(resultTask);
}
catch (Exception exception)
{
return new ValueTask<Response>(Response.FromException(exception));
}
}
private static async ValueTask<Response> CompleteInvokeAsync(ValueTask resultTask)
{
try
{
await resultTask;
return Response.Completed;
}
catch (Exception exception)
{
return Response.FromException(exception);
}
}
// Generated
protected abstract ValueTask InvokeInner();
}
[SerializerTransparent]
public abstract class TransactionRequest<TResult> : TransactionRequestBase
{
protected TransactionRequest(Serializer<OrleansTransactionAbortedException> exceptionSerializer, IServiceProvider serviceProvider) : base(exceptionSerializer, serviceProvider)
{
}
protected sealed override ValueTask<Response> BaseInvoke()
{
try
{
var resultTask = InvokeInner();
if (resultTask.IsCompleted)
{
return new ValueTask<Response>(Response.FromResult(resultTask.Result));
}
return CompleteInvokeAsync(resultTask);
}
catch (Exception exception)
{
return new ValueTask<Response>(Response.FromException(exception));
}
}
private static async ValueTask<Response> CompleteInvokeAsync(ValueTask<TResult> resultTask)
{
try
{
var result = await resultTask;
return Response.FromResult(result);
}
catch (Exception exception)
{
return Response.FromException(exception);
}
}
// Generated
protected abstract ValueTask<TResult> InvokeInner();
}
[SerializerTransparent]
public abstract class TransactionTaskRequest<TResult> : TransactionRequestBase
{
protected TransactionTaskRequest(Serializer<OrleansTransactionAbortedException> exceptionSerializer, IServiceProvider serviceProvider) : base(exceptionSerializer, serviceProvider)
{
}
protected sealed override ValueTask<Response> BaseInvoke()
{
try
{
var resultTask = InvokeInner();
var status = resultTask.Status;
if (resultTask.IsCompleted)
{
return new ValueTask<Response>(Response.FromResult(resultTask.GetAwaiter().GetResult()));
}
return CompleteInvokeAsync(resultTask);
}
catch (Exception exception)
{
return new ValueTask<Response>(Response.FromException(exception));
}
}
private static async ValueTask<Response> CompleteInvokeAsync(Task<TResult> resultTask)
{
try
{
var result = await resultTask;
return Response.FromResult(result);
}
catch (Exception exception)
{
return Response.FromException(exception);
}
}
// Generated
protected abstract Task<TResult> InvokeInner();
}
[SerializerTransparent]
public abstract class TransactionTaskRequest : TransactionRequestBase
{
protected TransactionTaskRequest(Serializer<OrleansTransactionAbortedException> exceptionSerializer, IServiceProvider serviceProvider) : base(exceptionSerializer, serviceProvider)
{
}
protected sealed override ValueTask<Response> BaseInvoke()
{
try
{
var resultTask = InvokeInner();
var status = resultTask.Status;
if (resultTask.IsCompleted)
{
resultTask.GetAwaiter().GetResult();
return new ValueTask<Response>(Response.Completed);
}
return CompleteInvokeAsync(resultTask);
}
catch (Exception exception)
{
return new ValueTask<Response>(Response.FromException(exception));
}
}
private static async ValueTask<Response> CompleteInvokeAsync(Task resultTask)
{
try
{
await resultTask;
return Response.Completed;
}
catch (Exception exception)
{
return Response.FromException(exception);
}
}
// Generated
protected abstract Task InvokeInner();
}
}