File: ProcessRequestAsyncResult.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 (281 lines) | stat: -rw-r--r-- 11,979 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
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//----------------------------------------------------------------

namespace System.ServiceModel.Routing
{
    using System;
    using System.Configuration;
    using System.Runtime;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Dispatcher;
    using System.ServiceModel.Security;
    using System.Threading;
    using System.Transactions;
    //using System.Security.Principal;

    class ProcessRequestAsyncResult<TContract> : TransactedAsyncResult
    {
        static AsyncCompletion operationCallback = new AsyncCompletion(OperationCallback);
        RoutingService service;
        IRoutingClient currentClient;
        MessageRpc messageRpc;
        Message replyMessage;
        bool allCompletedSync;
        bool abortedRetry;

        public ProcessRequestAsyncResult(RoutingService service, Message message, AsyncCallback callback, object state)
            : base(callback, state)
        {
            this.allCompletedSync = true;
            this.service = service;
            this.messageRpc = new MessageRpc(message, OperationContext.Current, service.ChannelExtension.ImpersonationRequired);
            if (TD.RoutingServiceProcessingMessageIsEnabled())
            {
                TD.RoutingServiceProcessingMessage(this.messageRpc.EventTraceActivity, this.messageRpc.UniqueID,
                    message.Headers.Action, this.messageRpc.OperationContext.EndpointDispatcher.EndpointAddress.Uri.ToString(), messageRpc.Transaction != null ? "True" : "False");
            }

            try
            {
                EndpointNameMessageFilter.Set(this.messageRpc.Message.Properties, service.ChannelExtension.EndpointName);
                this.messageRpc.RouteToSingleEndpoint<TContract>(this.service.RoutingConfig);
            }
            catch (MultipleFilterMatchesException matchesException)
            {
                // Wrap this exception with one that is more meaningful to users of RoutingService:
                throw FxTrace.Exception.AsError(new ConfigurationErrorsException(SR.ReqReplyMulticastNotSupported(this.messageRpc.OperationContext.Channel.LocalAddress), matchesException));
            }

            while (this.StartProcessing())
            {
            }
        }

        bool StartProcessing()
        {
            bool callAgain = false;            
            SendOperation sendOperation = this.messageRpc.Operations[0];
            this.currentClient = this.service.GetOrCreateClient<TContract>(sendOperation.CurrentEndpoint, this.messageRpc.Impersonating);

            if (TD.RoutingServiceTransmittingMessageIsEnabled())
            {
                TD.RoutingServiceTransmittingMessage(this.messageRpc.EventTraceActivity, this.messageRpc.UniqueID, "0", this.currentClient.Key.ToString());
            }
            
            try
            {
                if (messageRpc.Transaction != null && sendOperation.HasAlternate)
                {
                    throw FxTrace.Exception.AsError(new ConfigurationErrorsException(SR.ErrorHandlingNotSupportedReqReplyTxn(this.messageRpc.OperationContext.Channel.LocalAddress)));
                }

                // We always work on cloned message when there are backup endpoints to handle exception cases
                Message message;
                if (sendOperation.AlternateEndpointCount > 0)
                {
                    message = messageRpc.CreateBuffer().CreateMessage();
                }
                else
                {
                    message = messageRpc.Message;
                }

                sendOperation.PrepareMessage(message);

                IAsyncResult result = null;
                using (this.PrepareTransactionalCall(messageRpc.Transaction))
                {
                    IDisposable impersonationContext = null;
                    try
                    {
                        //Perform the assignment in a finally block so it won't be interrupted asynchronously
                        try { }
                        finally
                        {
                            impersonationContext = messageRpc.PrepareCall();
                        }
                        result = this.currentClient.BeginOperation(message, messageRpc.Transaction, this.PrepareAsyncCompletion(operationCallback), this);
                    }
                    finally
                    {
                        if (impersonationContext != null)
                        {
                            impersonationContext.Dispose();
                        }
                    }
                }

                if (this.CheckSyncContinue(result))
                {
                    if (this.OperationComplete(result))
                    {
                        this.Complete(this.allCompletedSync);
                    }
                    else
                    {
                        callAgain = true;
                    }
                }
            }
            catch (Exception exception)
            {
                if (Fx.IsFatal(exception))
                {
                    throw;
                }
                
                if (!this.HandleClientOperationFailure(exception))
                {
                    throw;
                }
                callAgain = true;
            }
            return callAgain;
        }

        static bool OperationCallback(IAsyncResult result)
        {
            ProcessRequestAsyncResult<TContract> thisPtr = (ProcessRequestAsyncResult<TContract>)result.AsyncState;
            FxTrace.Trace.SetAndTraceTransfer(thisPtr.service.ChannelExtension.ActivityID, true);
            thisPtr.allCompletedSync = false;

            try
            {
                if (thisPtr.OperationComplete(result))
                {
                    return true;
                }
            }
            catch (Exception exception)
            {
                if (Fx.IsFatal(exception))
                {
                    throw;
                }

                if (!thisPtr.HandleClientOperationFailure(exception))
                {
                    throw;
                }
            }

            while (thisPtr.StartProcessing())
            {
            }

            return false;
        }

        // Returns true if we're all done and can complete this AsyncResult now
        bool OperationComplete(IAsyncResult result)
        {
            bool completeSelf = false;
            Message responseMsg = this.currentClient.EndOperation(result);

            if (TD.RoutingServiceTransmitSucceededIsEnabled())
            {
                TD.RoutingServiceTransmitSucceeded(this.messageRpc.EventTraceActivity, this.messageRpc.UniqueID, "0", this.currentClient.Key.ToString());
            }

            if (responseMsg == null || !responseMsg.IsFault)
            {
                if (TD.RoutingServiceSendingResponseIsEnabled())
                {
                    string action = (responseMsg != null) ? responseMsg.Headers.Action : string.Empty;
                    TD.RoutingServiceSendingResponse(this.messageRpc.EventTraceActivity, action);
                }
            }
            else
            {
                if (TD.RoutingServiceSendingFaultResponseIsEnabled()) { TD.RoutingServiceSendingFaultResponse(this.messageRpc.EventTraceActivity, responseMsg.Headers.Action); }
            }
            this.replyMessage = responseMsg;
            completeSelf = true;

            if (TD.RoutingServiceCompletingTwoWayIsEnabled()) { TD.RoutingServiceCompletingTwoWay(this.messageRpc.EventTraceActivity); }
            return completeSelf;
        }

        internal static Message End(IAsyncResult result)
        {
            ProcessRequestAsyncResult<TContract> processRequest = AsyncResult.End<ProcessRequestAsyncResult<TContract>>(result);
            return processRequest.replyMessage;
        }

        bool HandleClientOperationFailure(Exception exception)
        {
            SendOperation sendOperation = this.messageRpc.Operations[0];
            if (TD.RoutingServiceTransmitFailedIsEnabled()) { TD.RoutingServiceTransmitFailed(this.messageRpc.EventTraceActivity, sendOperation.CurrentEndpoint.ToString(), exception); }

            if (!(exception is CommunicationException || exception is TimeoutException))
            {
                //We only move to backup for CommunicationExceptions and TimeoutExceptions
                return false;
            }

            if ((exception is CommunicationObjectAbortedException || exception is CommunicationObjectFaultedException) && 
                !this.service.ChannelExtension.HasSession)
            {
                // Messages on a non sessionful channel share outbound connections and can 
                // fail due to other messages failing on the same channel
                if (messageRpc.Transaction == null && !this.abortedRetry)
                {
                    //No session and non transactional, retry the message 1 time (before moving to backup)
                    this.abortedRetry = true;
                    return true;
                }
            }
            else if (exception is EndpointNotFoundException)
            {
                // The channel may not fault for this exception for bindings other than netTcpBinding
                // We abort the channel in that case. We proactively clean up so that we don't have to cleanup later
                SessionChannels sessionChannels = this.service.GetSessionChannels(this.messageRpc.Impersonating);
                if (sessionChannels != null)
                {
                    sessionChannels.AbortChannel(sendOperation.CurrentEndpoint);
                }
            }
            else if (exception is MessageSecurityException)
            {
                // The service may have been stopped and restarted without the routing service knowledge.
                // When we try to use a cached channel to the service, the channel can fault due to this exception
                // The faulted channel gets cleaned up and we retry one more time only when service has backup
                // If there is no backup, we do not retry since we do not create a buffered message to prevent performance degradation
                if (!this.abortedRetry && (sendOperation.AlternateEndpointCount > 0))
                {
                    this.abortedRetry = true;
                    return true;
                }
            }
            else if (exception is ProtocolException)
            {
                // This exception may happen when the current cached channel was closed due to end service recycles.
                // We abort the channel in this case and clean it up from the session.
                // We will then retry the request one more time only. In retried request, it will create a new channel because the cached channel has been cleaned up.
                if (!this.abortedRetry)
                {
                    SessionChannels sessionChannels = this.service.GetSessionChannels(this.messageRpc.Impersonating);
                    if (sessionChannels != null)
                    {
                        this.abortedRetry = true;
                        sessionChannels.AbortChannel(sendOperation.CurrentEndpoint);
                        return true;
                    }
                }
            }

            if (sendOperation.TryMoveToAlternate(exception))
            {
                if (TD.RoutingServiceMovedToBackupIsEnabled())
                {
                    TD.RoutingServiceMovedToBackup(this.messageRpc.EventTraceActivity, messageRpc.UniqueID, "0", sendOperation.CurrentEndpoint.ToString());
                }

                return true;
            }

            return false;
        }
    }
}