summaryrefslogtreecommitdiff
path: root/cs/src/Ice/ConnectRequestHandler.cs
blob: dddea0e2d1b320a23d4c118ca9a2da321238e375 (plain)
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
// **********************************************************************
//
// Copyright (c) 2003-2014 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Ice.Instrumentation;

namespace IceInternal
{
    public class ConnectRequestHandler : RequestHandler, Reference.GetConnectionCallback, RouterInfo.AddProxyCallback
    {
        private class Request
        {
            internal Request(BasicStream os)
            {
                this.os = new BasicStream(os.instance(), Ice.Util.currentProtocolEncoding);
                this.os.swap(os);
            }

            internal Request(OutgoingAsyncBase outAsync)
            {
                this.outAsync = outAsync;
            }

            internal OutgoingAsyncBase outAsync = null;
            internal BasicStream os = null;
            internal Ice.AsyncCallback sentCallback = null;
        }

        public RequestHandler connect(Ice.ObjectPrxHelperBase proxy)
        {
            //
            // Initiate the connection if connect() is called by the proxy that
            // created the handler.
            //
            if(Object.ReferenceEquals(proxy, _proxy) && _connect)
            {
                _connect = false; // Call getConnection only once
                _reference.getConnection(this);
            }

            try
            {
                lock(this)
                {
                    if(!initialized())
                    {
                        _proxies.Add(proxy);
                        return this;
                    }
                }
            }
            catch(Ice.LocalException ex)
            {
                throw ex;
            }

            if(_connectionRequestHandler != null)
            {
                proxy.setRequestHandler__(this, _connectionRequestHandler);
                return _connectionRequestHandler;
            }
            else
            {
                return this;                
            }
        }

        public RequestHandler update(RequestHandler previousHandler, RequestHandler newHandler)
        {
            return previousHandler == this ? newHandler : this;
        }

        public void prepareBatchRequest(BasicStream os)
        {
            lock(this)
            {
                while(_batchRequestInProgress)
                {
                    System.Threading.Monitor.Wait(this);
                }

                if(!initialized())
                {
                    _batchRequestInProgress = true;
                    _batchStream.swap(os);
                    return;
                }
            }
            _connection.prepareBatchRequest(os);
        }

        public void finishBatchRequest(BasicStream os)
        {
            lock(this)
            {
                if(!initialized()) // This can't throw until _batchRequestInProgress = false
                {
                    Debug.Assert(_batchRequestInProgress);
                    _batchRequestInProgress = false;
                    System.Threading.Monitor.PulseAll(this);

                    _batchStream.swap(os);

                    _requests.AddLast(new Request(_batchStream));
                    return;
                }
            }
            _connection.finishBatchRequest(os, _compress);
        }

        public void abortBatchRequest()
        {
            lock(this)
            {
                if(!initialized()) // This can't throw until _batchRequestInProgress = false
                {
                    Debug.Assert(_batchRequestInProgress);
                    _batchRequestInProgress = false;
                    System.Threading.Monitor.PulseAll(this);

                    BasicStream dummy = new BasicStream(_reference.getInstance(), Ice.Util.currentProtocolEncoding);
                    _batchStream.swap(dummy);

                    return;
                }
            }
            _connection.abortBatchRequest();
        }

        public bool sendAsyncRequest(OutgoingAsyncBase outAsync, out Ice.AsyncCallback sentCallback)
        {
            lock(this)
            {
                if(!_initialized)
                {
                    outAsync.cancelable(this); // This will throw if the request is canceled
                }

                try
                {
                    if(!initialized())
                    {
                        _requests.AddLast(new Request(outAsync));
                        sentCallback = null;
                        return false;
                    }
                }
                catch(Ice.LocalException ex)
                {
                    throw new RetryException(ex);
                }
            }
            return outAsync.send(_connection, _compress, _response, out sentCallback);
        }

        public void asyncRequestCanceled(OutgoingAsyncBase outAsync, Ice.LocalException ex)
        {
            lock(this)
            {
                if(_exception != null)
                {
                    return; // The request has been notified of a failure already.
                }

                if(!initialized())
                {
                    LinkedListNode<Request> p = _requests.First;
                    while(p != null)
                    {
                        Request request = p.Value;
                        if(request.outAsync == outAsync)
                        {
                            _requests.Remove(p);
                            Ice.AsyncCallback cb = outAsync.completed(ex);
                            if(cb != null)
                            {
                                outAsync.invokeCompletedAsync(cb);
                            }
                            return;
                        }
                        p = p.Next;
                    }
                    Debug.Assert(false); // The request has to be queued if it timed out and we're not initialized yet.
                }
            }
            _connection.asyncRequestCanceled(outAsync, ex);
        }

        public Reference getReference()
        {
            return _reference;
        }

        public Ice.ConnectionI getConnection()
        {
            lock(this)
            {
                if(_exception != null)
                {
                    throw _exception;
                }
                else
                {
                    return _connection;
                }
            }
        }

        public Ice.ConnectionI waitForConnection()
        {
            lock(this)
            {
                if(_exception != null)
                {
                    throw new RetryException(_exception);
                }
                //
                // Wait for the connection establishment to complete or fail.
                //
                while(!_initialized && _exception == null)
                {
                    System.Threading.Monitor.Wait(this);
                }
                return getConnection();
            }
        }

        //
        // Implementation of Reference.GetConnectionCallback
        //

        public void setConnection(Ice.ConnectionI connection, bool compress)
        {
            lock(this)
            {
                Debug.Assert(_exception == null && _connection == null);
                _connection = connection;
                _compress = compress;
            }

            //
            // If this proxy is for a non-local object, and we are using a router, then
            // add this proxy to the router info object.
            //
            RouterInfo ri = _reference.getRouterInfo();
            if(ri != null && !ri.addProxy(_proxy, this))
            {
                return; // The request handler will be initialized once addProxy returns.
            }

            //
            // We can now send the queued requests.
            //
            flushRequests();
        }

        public void setException(Ice.LocalException ex)
        {
            lock(this)
            {
                Debug.Assert(!_initialized && _exception == null);
                _exception = ex;
                _proxies.Clear();
                _proxy = null; // Break cyclic reference count.

                //
                // NOTE: remove the request handler *before* notifying the
                // requests that the connection failed. It's important to ensure
                // that future invocations will obtain a new connect request
                // handler once invocations are notified.
                //
                try
                {
                    _reference.getInstance().requestHandlerFactory().removeRequestHandler(_reference, this);
                }
                catch(Ice.CommunicatorDestroyedException)
                {
                    // Ignore
                }

                foreach(Request request in _requests)
                {
                    if(request.outAsync != null)
                    {
                        Ice.AsyncCallback cb = request.outAsync.completed(_exception);
                        if(cb != null)
                        {
                            request.outAsync.invokeCompletedAsync(cb);
                        }
                    }
                }
                _requests.Clear();
                System.Threading.Monitor.PulseAll(this);
            }
        }

        //
        // Implementation of RouterInfo.AddProxyCallback
        //
        public void addedProxy()
        {
            //
            // The proxy was added to the router info, we're now ready to send the
            // queued requests.
            //
            flushRequests();
        }

        public ConnectRequestHandler(Reference @ref, Ice.ObjectPrx proxy)
        {
            _reference = @ref;
            _connect = true;
            _response = _reference.getMode() == Reference.Mode.ModeTwoway;
            _proxy = (Ice.ObjectPrxHelperBase)proxy;
            _initialized = false;
            _flushing = false;
            _batchRequestInProgress = false;
            _batchStream = new BasicStream(@ref.getInstance(), Ice.Util.currentProtocolEncoding);
        }

        private bool initialized()
        {
            if(_initialized)
            {
                Debug.Assert(_connection != null);
                return true;
            }
            else
            {
                while(_flushing && _exception == null)
                {
                    System.Threading.Monitor.Wait(this);
                }

                if(_exception != null)
                {
                    throw _exception;
                }
                else
                {
                    return _initialized;
                }
            }
        }

        private void flushRequests()
        {
            lock(this)
            {
                Debug.Assert(_connection != null && !_initialized);

                while(_batchRequestInProgress)
                {
                    System.Threading.Monitor.Wait(this);
                }

                //
                // We set the _flushing flag to true to prevent any additional queuing. Callers
                // might block for a little while as the queued requests are being sent but this
                // shouldn't be an issue as the request sends are non-blocking.
                //
                _flushing = true;
            }

            LinkedListNode<Request> p = _requests.First; // _requests is immutable when _flushing = true
            Ice.LocalException exception = null;
            while(p != null)
            {
                Request request = p.Value;
                try
                {
                    if(request.os != null)
                    {
                        BasicStream os = new BasicStream(request.os.instance(), Ice.Util.currentProtocolEncoding);
                        _connection.prepareBatchRequest(os);
                        try
                        {
                            request.os.pos(0);
                            os.writeBlob(request.os.readBlob(request.os.size()));
                        }
                        catch(Ice.LocalException)
                        {
                            _connection.abortBatchRequest();
                            throw;
                        }
                        _connection.finishBatchRequest(os, _compress);
                    }
                    else if(request.outAsync.send(_connection, _compress, _response, out request.sentCallback))
                    {
                        if(request.sentCallback != null)
                        {
                            request.outAsync.invokeSentAsync(request.sentCallback);
                        }
                    }
                }
                catch(RetryException ex)
                {
                    exception = ex.get();
                    try
                    {
                        // Remove the request handler before retrying.
                        _reference.getInstance().requestHandlerFactory().removeRequestHandler(_reference, this);
                    }
                    catch(Ice.CommunicatorDestroyedException)
                    {
                        // Ignore
                    }
                    request.outAsync.retryException(ex.get());
                }
                catch(Ice.LocalException ex)
                {
                    exception = ex;
                    Ice.AsyncCallback cb = request.outAsync.completed(ex);
                    if(cb != null)
                    {
                        request.outAsync.invokeCompletedAsync(cb);
                    }
                }
                LinkedListNode<Request> tmp = p;
                p = p.Next;
                _requests.Remove(tmp);
            }

            //
            // If we aren't caching the connection, don't bother creating a
            // connection request handler. Otherwise, update the proxies
            // request handler to use the more efficient connection request
            // handler.
            //
            if(_reference.getCacheConnection() && exception == null)
            {
                _connectionRequestHandler = new ConnectionRequestHandler(_reference, _connection, _compress);
                foreach(Ice.ObjectPrxHelperBase prx in _proxies)
                {
                    prx.setRequestHandler__(this, _connectionRequestHandler);
                }
            }

            lock(this)
            {
                Debug.Assert(!_initialized);
                _exception = exception;
                _initialized = _exception == null;
                _flushing = false;
                try
                {
                    //
                    // Only remove once all the requests are flushed to
                    // guarantee serialization.
                    //
                    _reference.getInstance().requestHandlerFactory().removeRequestHandler(_reference, this);
                }
                catch(Ice.CommunicatorDestroyedException)
                {
                    // Ignore
                }
                _proxies.Clear();
                _proxy = null; // Break cyclic reference count.
                System.Threading.Monitor.PulseAll(this);
            }
        }

        private Reference _reference;
        private bool _connect;
        private bool _response;

        private Ice.ObjectPrxHelperBase _proxy;
        private HashSet<Ice.ObjectPrxHelperBase> _proxies = new HashSet<Ice.ObjectPrxHelperBase>();

        private Ice.ConnectionI _connection;
        private bool _compress;
        private Ice.LocalException _exception;
        private bool _initialized;
        private bool _flushing;

        private LinkedList<Request> _requests = new LinkedList<Request>();
        private bool _batchRequestInProgress;
        private BasicStream _batchStream;

        private RequestHandler _connectionRequestHandler;
    }
}