File: WorkBatch.cs

package info (click to toggle)
mono 6.14.1%2Bds2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,282,732 kB
  • sloc: cs: 11,182,461; xml: 2,850,281; ansic: 699,123; cpp: 122,919; perl: 58,604; javascript: 30,841; asm: 21,845; makefile: 19,602; sh: 10,973; python: 4,772; pascal: 925; sql: 859; sed: 16; php: 1
file content (446 lines) | stat: -rw-r--r-- 13,808 bytes parent folder | download | duplicates (7)
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
#pragma warning disable 1634, 1691
using System;
using System.Diagnostics;
using System.Transactions;
using System.Collections;
using System.Collections.Generic;
using System.Workflow.Runtime.Hosting;

namespace System.Workflow.Runtime
{
    #region Runtime Batch Implementation

    #region WorkBatch

    internal enum WorkBatchState
    {
        Usable,
        Merged,
        Completed
    }

    /// <summary>
    /// Summary description for Work Batching. 
    /// </summary>
    internal sealed class WorkBatch : IWorkBatch, IDisposable
    {
        private PendingWorkCollection _pendingWorkCollection;
        private object mutex = new object();
        private WorkBatchState _state;
        private WorkBatchCollection _collection = null;

        private WorkBatch()
        {
        }

        internal WorkBatch(WorkBatchCollection workBackCollection)
        {
            _pendingWorkCollection = new PendingWorkCollection();
            _state = WorkBatchState.Usable;
            _collection = workBackCollection;
        }

        internal int Count
        {
            get { return _pendingWorkCollection.WorkItems.Count; }
        }

        internal void SetWorkBatchCollection(WorkBatchCollection workBatchCollection)
        {
            _collection = workBatchCollection;
        }

        #region IWorkBatch Implementation
        /// <summary>
        /// Add Work to Batch
        /// </summary>
        /// <param name="work"></param>
        /// <param name="workItem"></param>
        void IWorkBatch.Add(IPendingWork work, object workItem)
        {
            if (_pendingWorkCollection == null)
                throw new ObjectDisposedException("WorkBatch");

            lock (this.mutex)
            {
                System.Diagnostics.Debug.Assert(this._state == WorkBatchState.Usable, "Trying to add to unusable batch.");

                _pendingWorkCollection.Add(work, _collection.GetNextWorkItemOrderId(work), workItem);
            }
        }
        #endregion

        #region Internal Implementation

        internal bool IsDirty
        {
            get
            {
                return this._pendingWorkCollection.IsDirty;
            }
        }
        /// <summary>
        /// This one commits all the pending work and its items 
        /// added so far in this batch.
        /// </summary>
        /// <param name="transaction"></param>
        internal void Commit(Transaction transaction)
        {
            lock (this.mutex)
            {
                _pendingWorkCollection.Commit(transaction);
            }
        }


        /// <summary>
        /// This one completes the pending work
        /// </summary>
        /// <param name="succeeded"></param>
        internal void Complete(bool succeeded)
        {
            lock (this.mutex)
            {
                if (this._pendingWorkCollection.IsUsable)
                {
                    _pendingWorkCollection.Complete(succeeded);
                    _pendingWorkCollection.Dispose();
                    this._state = WorkBatchState.Completed;
                }
            }
        }

        /// <summary>
        /// API for Runtime to call to do Merge Operation: Right now 
        /// we dont use this because we dont support incoming work collection.
        /// </summary>
        /// <param name="batch"></param>
        internal void Merge(WorkBatch batch)
        {
            if (batch == null)
                return; //nothing to merge

            if (_pendingWorkCollection == null)
                throw new ObjectDisposedException("WorkBatch");

            lock (this.mutex)
            {
                lock (batch.mutex)
                {
                    foreach (KeyValuePair<IPendingWork, SortedList<long, object>> item in batch._pendingWorkCollection.WorkItems)
                    {
                        //_pendingWorkCollection.AddRange(item.Key, item.Value);
                        SortedList<long, object> newItems = item.Value;
                        foreach (KeyValuePair<long, object> kvp in newItems)
                            _pendingWorkCollection.Add(item.Key, kvp.Key, kvp.Value);
                    }
                }

                this._state = WorkBatchState.Merged;
            }
        }
        #endregion

        #region IDisposable Members
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                _pendingWorkCollection.Dispose();
                _pendingWorkCollection = null;
            }
        }
        #endregion

        #region PendingWorkCollection implementation

        /// <summary>
        /// Pending Work Implementation
        /// </summary>
        internal sealed class PendingWorkCollection : IDisposable
        {
            Dictionary<IPendingWork, SortedList<long, object>> Items;

            #region Internal Implementation
            internal PendingWorkCollection()
            {
                Items = new Dictionary<IPendingWork, SortedList<long, object>>();
            }

            internal Dictionary<IPendingWork, SortedList<long, object>> WorkItems
            {
                get
                {
                    return Items;
                }
            }

            internal bool IsUsable
            {
                get
                {
                    return this.Items != null;
                }
            }

            internal bool IsDirty
            {
                get
                {
                    if (!this.IsUsable)
                        return false;

                    //
                    // Loop through all pending work items in the collection
                    // If any of them assert that they need to commit than the batch is dirty
                    foreach (KeyValuePair<IPendingWork, SortedList<long, object>> workItem in this.WorkItems)
                    {
                        try
                        {
                            IPendingWork work = workItem.Key;
                            if (work.MustCommit(workItem.Value))
                                return true;
                        }
                        catch (Exception e)
                        {
                            if (WorkflowExecutor.IsIrrecoverableException(e))
                            {
#pragma warning disable 56503
                                throw;
#pragma warning restore 56503
                            }
                            else
                            {
                                // Ignore exceptions and treat condition as false return value;
                            }
                        }
                    }
                    //
                    // If no one asserted that they need to commit we're not dirty
                    return false;
                }
            }

            internal void Add(IPendingWork work, long orderId, object workItem)
            {
                SortedList<long, object> workItems = null;

                if (!Items.TryGetValue(work, out workItems))
                {
                    workItems = new SortedList<long, object>();
                    Items.Add(work, workItems);
                }
                Debug.Assert(!workItems.ContainsKey(orderId), string.Format(System.Globalization.CultureInfo.InvariantCulture, "List already contains key {0}", orderId));
                workItems.Add(orderId, workItem);
                WorkflowTrace.Runtime.TraceEvent(TraceEventType.Information, 0, "pending work hc {0} added workItem hc {1}", work.GetHashCode(), workItem.GetHashCode());
            }

            //Commit All Pending Work
            internal void Commit(Transaction transaction)
            {
                //ignore items param
                foreach (KeyValuePair<IPendingWork, SortedList<long, object>> workItem in Items)
                {
                    IPendingWork work = workItem.Key;
                    List<object> values = new List<object>(workItem.Value.Values);
                    work.Commit(transaction, values);
                }
            }

            //Complete All Pending Work
            internal void Complete(bool succeeded)
            {
                foreach (KeyValuePair<IPendingWork, SortedList<long, object>> workItem in Items)
                {
                    IPendingWork work = workItem.Key;
                    List<object> values = new List<object>(workItem.Value.Values);
                    try
                    {
                        work.Complete(succeeded, values);
                    }
                    catch (Exception e)
                    {
                        if (WorkflowExecutor.IsIrrecoverableException(e))
                        {
                            throw;
                        }
                        else
                        {
                            WorkflowTrace.Runtime.TraceEvent(TraceEventType.Warning, 0, "Work Item {0} threw exception on complete notification", workItem.GetType());
                        }
                    }
                }
            }

            #endregion

            #region IDisposable Members
            public void Dispose()
            {
                Dispose(true);
                GC.SuppressFinalize(this);
            }

            private void Dispose(bool disposing)
            {
                if (disposing && Items != null)
                {
                    Items.Clear();
                    Items = null;
                }
            }

            #endregion
        }
        #endregion
    }
    #endregion

    #region WorkBatchCollection
    /// <summary>
    /// collection of name to Batch
    /// </summary>
    internal sealed class WorkBatchCollection : Dictionary<object, WorkBatch>
    {
        object transientBatchID = new object();
        private object mutex = new object();
        //
        // All access must be through Interlocked.* methods
        private long _workItemOrderId = 0;

        internal long WorkItemOrderId
        {
            get
            {
                return Threading.Interlocked.Read(ref _workItemOrderId);
            }
            set
            {
                Debug.Assert(value >= _workItemOrderId, "New value for WorkItemOrderId must be greater than the current value");
                lock (mutex)
                {
                    _workItemOrderId = value;
                }
            }
        }

        internal long GetNextWorkItemOrderId(IPendingWork pendingWork)
        {
            return Threading.Interlocked.Increment(ref _workItemOrderId);
        }
        /// <summary>
        /// A new batch is created per atomic scope or any
        /// required sub batches. An example of an optional sub batch
        /// could be a batch created for Send activities
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        internal IWorkBatch GetBatch(object id)
        {
            WorkBatch batch = null;

            lock (mutex)
            {
                if (this.TryGetValue(id, out batch))
                    return batch;

                batch = new WorkBatch(this);
                Add(id, batch);
            }

            return batch;
        }

        /// <summary>
        /// Find a batch for a given id without creating it.
        /// </summary>
        /// <param name="id">batch key</param>
        /// <returns>batch or null if not found</returns>
        private WorkBatch FindBatch(object id)
        {
            WorkBatch batch = null;
            lock (mutex)
            {
                TryGetValue(id, out batch);
            }

            return batch;
        }

        internal IWorkBatch GetTransientBatch()
        {
            return GetBatch(transientBatchID);
        }

        internal WorkBatch GetMergedBatch()
        {
            lock (mutex)
            {
                WorkBatch batch = new WorkBatch(this);

                foreach (WorkBatch existingBatch in this.Values)
                {
                    batch.Merge(existingBatch);
                }
                //Copy of all the items merged in one batch.
                //Order is preserved in the same way batches are created.
                return batch;
            }
        }

        internal void RollbackBatch(object id)
        {
            lock (mutex)
            {
                WorkBatch batch = FindBatch(id);
                if (batch != null)
                {
                    batch.Complete(false);
                    batch.Dispose();
                    Remove(id);
                }
            }
        }

        // Rollback all sub batches, calling "complete(false)" on all entries.
        internal void RollbackAllBatchedWork()
        {
            lock (mutex)
            {
                foreach (WorkBatch batch in this.Values)
                {
                    batch.Complete(false);
                    batch.Dispose();
                }
                Clear(); // clear the collection
            }
        }

        // Clear sub batches after successful commit/complete.
        internal void ClearSubBatches()
        {
            lock (mutex)
            {
                foreach (WorkBatch existingBatch in this.Values)
                {
                    existingBatch.Dispose();
                }
                Clear(); // clear the collection
            }
        }

        internal void ClearTransientBatch()
        {
            RollbackBatch(transientBatchID);
        }
    }
    #endregion

    #endregion
}