[System] EndRead now throws WebException on abort.
[mono.git] / mcs / class / System.ServiceModel / System.ServiceModel / DuplexClientRuntimeChannel.cs
1 //
2 // DuplexClientRuntimeChannel.cs
3 //
4 // Author:
5 //      Atsushi Enomoto <atsushi@ximian.com>
6 //
7 // Copyright (C) 2009 Novell, Inc.  http://www.novell.com
8 //
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
16 // 
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 // 
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 //
28 using System;
29 using System.Collections.Generic;
30 using System.Linq;
31 using System.Reflection;
32 using System.ServiceModel.Channels;
33 using System.ServiceModel.Description;
34 using System.ServiceModel.Dispatcher;
35 using System.ServiceModel.Security;
36 using System.Threading;
37 using System.Xml;
38
39 namespace System.ServiceModel.MonoInternal
40 {
41 #if DISABLE_REAL_PROXY
42         // FIXME: This is a quick workaround for bug #571907
43         public
44 #endif
45         class DuplexClientRuntimeChannel
46                 : ClientRuntimeChannel, IDuplexContextChannel
47         {
48                 public DuplexClientRuntimeChannel (ServiceEndpoint endpoint,
49                         ChannelFactory factory, EndpointAddress remoteAddress, Uri via)
50                         : base (endpoint, factory, remoteAddress, via)
51                 {
52                         var ed = new EndpointDispatcher (remoteAddress, endpoint.Contract.Name, endpoint.Contract.Namespace);
53                         ed.InitializeServiceEndpoint (true, null, endpoint);
54                         Runtime.CallbackDispatchRuntime = ed.DispatchRuntime;
55                 }
56
57                 public bool AutomaticInputSessionShutdown {
58                         get { throw new NotImplementedException (); }
59                         set { throw new NotImplementedException (); }
60                 }
61
62                 InstanceContext callback_instance;
63
64                 public InstanceContext CallbackInstance {
65                         get { return callback_instance; }
66                         set {
67                                 callback_instance = value;
68                                 Runtime.CallbackDispatchRuntime.InstanceContextProvider = new CallbackInstanceContextProvider (callback_instance);
69                         }
70                 }
71
72                 Action<TimeSpan> session_shutdown_delegate;
73
74                 public void CloseOutputSession (TimeSpan timeout)
75                 {
76                         throw new NotImplementedException ();
77                 }
78
79                 public IAsyncResult BeginCloseOutputSession (TimeSpan timeout, AsyncCallback callback, object state)
80                 {
81                         if (session_shutdown_delegate == null)
82                                 session_shutdown_delegate = new Action<TimeSpan> (CloseOutputSession);
83                         return session_shutdown_delegate.BeginInvoke (timeout, callback, state);
84                 }
85
86                 public void EndCloseOutputSession (IAsyncResult result)
87                 {
88                         session_shutdown_delegate.EndInvoke (result);
89                 }
90
91                 // listener loop manager
92
93                 bool loop;
94
95                 TimeSpan receive_timeout;
96                 bool receive_synchronously = true; // FIXME
97
98                 IAsyncResult loop_result;
99                 AutoResetEvent loop_handle = new AutoResetEvent (false);
100                 AutoResetEvent finish_handle = new AutoResetEvent (false);
101                 AutoResetEvent receive_reply_handle = new AutoResetEvent (false);
102
103                 protected override void OnOpen (TimeSpan timeout)
104                 {
105                         loop = true;
106                         base.OnOpen (timeout);
107                         receive_timeout = TimeSpan.FromSeconds (10);
108                 }
109
110                 protected override void OnOpened ()
111                 {
112                         base.OnOpened ();
113                         loop_result = new Action<IInputChannel> (ProcessRequestOrInput).BeginInvoke (DuplexChannel, null, null);
114                 }
115
116                 protected override void OnClose (TimeSpan timeout)
117                 {
118                         DateTime start = DateTime.Now;
119                         base.OnClose (timeout);
120                         loop = false;
121                         if (!loop_handle.WaitOne (timeout - (DateTime.Now - start)))
122                                 throw new TimeoutException ();
123                         if (!finish_handle.WaitOne (timeout - (DateTime.Now - start)))
124                                 throw new TimeoutException ();
125                 }
126
127                 void ProcessRequestOrInput (IInputChannel input)
128                 {
129                         while (true) {
130                                 if (!loop)
131                                         return;
132
133                                 if (receive_synchronously) {
134                                         Message msg;
135                                         if (input.TryReceive (receive_timeout, out msg))
136                                                 ProcessInput (input, msg);
137                                 } else {
138                                         input.BeginTryReceive (receive_timeout, TryReceiveDone, input);
139                                         loop_handle.WaitOne (receive_timeout);
140                                 }
141                         }
142                 }
143
144                 void TryReceiveDone (IAsyncResult result)
145                 {
146                         try {
147                                 Message msg;
148                                 var input = (IInputChannel) result.AsyncState;
149                                 if (input.EndTryReceive (result, out msg)) {
150                                         loop_handle.Set ();
151                                         ProcessInput (input, msg);
152                                 }
153                         } catch (Exception ex) {
154                                 // FIXME: rather log it
155                                 Console.WriteLine ("Error at duplex client receiver side");
156                                 Console.WriteLine (ex);
157                                 loop = false;
158                         }
159                 }
160
161                 void ProcessInputCore (IInputChannel input, Message message)
162                 {
163                                 bool isReply = message != null && Contract.Operations.Any (od => (od.DeclaringContract.CallbackContractType == od.DeclaringContract.ContractType || !od.InCallbackContract) && od.Messages.Any (md => md.Action == message.Headers.Action));
164                                 if (isReply) {
165                                         if (ReplyHandlerQueue.Count > 0) {
166                                                 if (isReply) {
167                                                         var h = ReplyHandlerQueue.Dequeue ();
168                                                         h (message);
169                                                         return;
170                                                 }
171                                         }
172                                 }
173                                 
174                                 if (message.IsFault) {
175                                         Exception ex;
176                                         var mf = MessageFault.CreateFault (message, 0x10000);
177                                         if (FaultConverter.GetDefaultFaultConverter (message.Version).TryCreateException (message, mf, out ex)) // FIXME: get maxMessageSize somehow
178                                                 throw ex;
179                                         else
180                                                 throw new FaultException (mf);
181                                 }
182                                 
183                                 if (!MessageMatchesEndpointDispatcher (message, Runtime.CallbackDispatchRuntime.EndpointDispatcher))
184                                         throw new EndpointNotFoundException (String.Format ("The request message has the target '{0}' with action '{1}' which is not reachable in this service contract", message.Headers.To, message.Headers.Action));
185                                 new InputOrReplyRequestProcessor (Runtime.CallbackDispatchRuntime, input).ProcessInput (message);
186                 }
187
188                 void ProcessInput (IInputChannel input, Message message)
189                 {
190                         try {
191                                 ProcessInputCore (input, message);
192                         } catch (Exception ex) {
193                                 // FIXME: log it.
194                                 Console.WriteLine (ex);
195                         } finally {
196                                 // unless it is closed by session/call manager, move it back to the loop to receive the next message.
197                                 if (loop && input.State != CommunicationState.Closed)
198                                         ProcessRequestOrInput (input);
199                         }
200                 }
201
202                 bool MessageMatchesEndpointDispatcher (Message req, EndpointDispatcher endpoint)
203                 {
204                         // FIXME: no need to filter address? It'd be mostly anonymous URI though.
205
206                         return endpoint.ContractFilter.Match (req);
207                 }
208                 
209                 internal override Message RequestCorrelated (Message msg, TimeSpan timeout, IOutputChannel channel)
210                 {
211                         DateTime startTime = DateTime.Now;
212                         Message ret = null;
213                         ManualResetEvent wait = new ManualResetEvent (false);
214                         Action<Message> handler = delegate (Message reply) {
215                                 ret = reply;
216                                 wait.Set ();
217                         };
218                         ReplyHandlerQueue.Enqueue (handler);
219                         channel.Send (msg, timeout);
220                         if (ret == null && !wait.WaitOne (timeout - (DateTime.Now - startTime)))
221                                 throw new TimeoutException ();
222                         return ret;
223                 }
224                 
225                 internal Queue<Action<Message>> ReplyHandlerQueue = new Queue<Action<Message>> ();
226         }
227 }