summaryrefslogtreecommitdiff
path: root/dotnet/client-010/client/transport/Session.cs
blob: 7b4aff98111feff88632763c151b3299d784e799 (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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using org.apache.qpid.transport.util;
using Frame = org.apache.qpid.transport.network.Frame;
using Logger = org.apache.qpid.transport.util.Logger;


namespace org.apache.qpid.transport
{
    /// <summary>
    ///  Session
    /// 
    /// </summary>
    public class Session : Invoker, ISession
    {
        private static readonly Logger log = Logger.Get(typeof (Session));
        private static readonly bool ENABLE_REPLAY;

        static Session()
        {
            const string enableReplay = "enable_command_replay";
            try
            {
                String var = Environment.GetEnvironmentVariable(enableReplay);
                if (var != null)
                {
                    ENABLE_REPLAY = bool.Parse(var);
                }
            }
            catch (Exception)
            {
                ENABLE_REPLAY = false;
            }
        }

        private readonly byte[] _name;
        private const long _timeout = 600000;
        private bool _autoSync = false;

        // channel may be null
        private Channel _channel;

        // incoming command count
        private int _commandsIn = 0;
        // completed incoming commands
        private readonly Object _processedLock = new Object();
        private RangeSet _processed = new RangeSet();
        private int _maxProcessed = - 1;
        private int _syncPoint = -1;

        // outgoing command count
        private int _commandsOut = 0;
        private readonly Dictionary<int, Method> _commands = new Dictionary<int, Method>();
        private int _maxComplete = - 1;
        private bool _needSync = false;
        private bool _closed;
        private readonly Dictionary<int, IFuture> _results = new Dictionary<int, IFuture>();
        private readonly List<ExecutionException> _exceptions = new List<ExecutionException>();


        public bool IsClosed
        {
            get
            {
                lock (this)
                {
                    return _closed;
                }
            }
            set
            {
                lock (this)
                {
                    _closed = value;
                }
            }
        }

        public string Name
        {
            get
            {
                ASCIIEncoding enc = new ASCIIEncoding();
                return enc.GetString(_name);
            }
        }

        public Session(byte[] name)
        {
            _name = name;
        }

        public byte[] GetName()
        {
            return _name;
        }

        public void SetAutoSync(bool value)
        {
            lock (_commands)
            {
                _autoSync = value;
            }
        }

        public Dictionary<int, Method> GetOutstandingCommands()
        {
            return _commands;
        }

        public int GetCommandsOut()
        {
            return _commandsOut;
        }

        public int CommandsIn
        {
            get { return _commandsIn; }
            set { _commandsIn = value; }
        }

        public int NextCommandId()
        {
            return _commandsIn++;
        }

        public void Identify(Method cmd)
        {
            int id = NextCommandId();
            cmd.Id = id;

            if (log.IsDebugEnabled())
            {
                log.Debug("ID: [{0}] %{1}", _channel, id);
            }

            //if ((id % 65536) == 0)
            if ((id & 0xff) == 0)
            {
                FlushProcessed(Option.TIMELY_REPLY);
            }
        }

        public void Processed(Method command)
        {
            Processed(command.Id);
        }

        public void Processed(int command)
        {
            Processed(new Range(command, command));
        }

        public void Processed(int lower, int upper)
        {
            Processed(new Range(lower, upper));
        }

        public void Processed(Range range)
        {
            log.Debug("{0} processed({1})", this, range);

            bool flush;
            lock (_processedLock)
            {
                _processed.Add(range);
                Range first = _processed.GetFirst();
                int lower = first.Lower;
                int upper = first.Upper;
                int old = _maxProcessed;
                if (Serial.Le(lower, _maxProcessed + 1))
                {
                    _maxProcessed = Serial.Max(_maxProcessed, upper);
                }
                flush = Serial.Lt(old, _syncPoint) && Serial.Ge(_maxProcessed, _syncPoint);
                _syncPoint = _maxProcessed;
            }
            if (flush)
            {
                FlushProcessed();
            }
        }

        public void FlushProcessed(params Option[] options)
        {
            RangeSet copy;
            lock (_processedLock)
            {
                copy = _processed.Copy();
            }
            SessionCompleted(copy, options);
        }

        public void KnownComplete(RangeSet kc)
        {
            lock (_processedLock)
            {
                RangeSet newProcessed = new RangeSet();
                foreach (Range pr in _processed)
                {
                    foreach (Range kr in kc)
                    {
                        foreach (Range r in pr.Subtract(kr))
                        {
                            newProcessed.Add(r);
                        }
                    }
                }
                _processed = newProcessed;
            }
        }

        public void SyncPoint()
        {
            int id = CommandsIn - 1;
            log.Debug("{0} synced to {1}", this, id);
            bool flush;
            lock (_processedLock)
            {
                _syncPoint = id;
                flush = Serial.Ge(_maxProcessed, _syncPoint);
            }
            if (flush)
            {
                FlushProcessed();
            }
        }

        public void Attach(Channel channel)
        {
            _channel = channel;
            _channel.Session = this;
        }

        public Method GetCommand(int id)
        {
            lock (_commands)
            {
                return _commands[id];
            }
        }

        public bool Complete(int lower, int upper)
        {
            //avoid autoboxing
            if (log.IsDebugEnabled())
            {
                log.Debug("{0} complete({1}, {2})", this, lower, upper);
            }
            lock (_commands)
            {
                int old = _maxComplete;
                for (int id = Serial.Max(_maxComplete, lower); Serial.Le(id, upper); id++)
                {
                    _commands.Remove(id);
                }
                if (Serial.Le(lower, _maxComplete + 1))
                {
                    _maxComplete = Serial.Max(_maxComplete, upper);
                }
                log.Debug("{0} commands remaining: {1}", this, _commands);
                Monitor.PulseAll(_commands);
                return Serial.Gt(_maxComplete, old);
            }
        }

        protected override void Invoke(Method m)
        {
            if (IsClosed)
            {
                List<ExecutionException> exc = GetExceptions();
                if (exc.Count > 0)
                {
                    throw new SessionException(exc);
                }
                else if (_close != null)
                {
                    throw new ConnectionException(_close);
                }
                else
                {
                    throw new SessionClosedException();
                }
            }

            if (m.EncodedTrack == Frame.L4)
            {
                lock (_commands)
                {
                    int next = _commandsOut++;
                    m.Id = next;
                    if (next == 0)
                    {
                        SessionCommandPoint(0, 0);
                    }
                    if (ENABLE_REPLAY)
                    {
                        _commands.Add(next, m);
                    }
                    if (_autoSync)
                    {
                        m.Sync = true;
                    }
                    _needSync = ! m.Sync;
                    _channel.Method(m);
                    if (_autoSync)
                    {
                        Sync();
                    }

                    // flush every 64K commands to avoid ambiguity on
                    // wraparound
                    if ((next%65536) == 0)
                    {
                        SessionFlush(Option.COMPLETED);
                    }
                }
            }
            else
            {
                _channel.Method(m);
            }
        }

        public void Sync()
        {
            Sync(_timeout);
        }

        public void Sync(long timeout)
        {
            log.Debug("{0} sync()", this);
            lock (_commands)
            {
                int point = _commandsOut - 1;

                if (_needSync && Serial.Lt(_maxComplete, point))
                {
                    ExecutionSync(Option.SYNC);
                }

                DateTime start = DateTime.Now;
                long elapsed = 0;

                while (!IsClosed && elapsed < timeout && Serial.Lt(_maxComplete, point))
                {
                    log.Debug("{0}   waiting for[{1}]: {2}, {3}", this, point,
                              _maxComplete, _commands);
                    Monitor.Wait(_commands, (int) (timeout - elapsed));
                    elapsed = DateTime.Now.Subtract(start).Milliseconds;
                }

                if (Serial.Lt(_maxComplete, point))
                {
                    if (IsClosed)
                    {
                        throw new SessionException(GetExceptions());
                    }
                    else
                    {
                        throw new Exception
                            (String.Format
                                 ("timed out waiting for sync: complete = {0}, point = {1}", _maxComplete, point));
                    }
                }
            }
        }


        public void Result(int command, Struct result)
        {
            IFuture future;
            lock (_results)
            {
                if (_results.ContainsKey(command))
                {
                    future = _results[command];
                    _results.Remove(command);
                }
                else
                {
                    throw new Exception(String.Format("Cannot ger result {0} for {1}", command, result));
                }
            }
            future.Result = result;
        }

        public void AddException(ExecutionException exc)
        {
            lock (_exceptions)
            {
                _exceptions.Add(exc);
            }
        }

        private ConnectionClose _close = null;

        public void CloseCode(ConnectionClose close)
        {
            _close = close;
        }

        public List<ExecutionException> GetExceptions()
        {
            lock (_exceptions)
            {
                return new List<ExecutionException>(_exceptions);
            }
        }

        public override IFuture Invoke(Method m, IFuture future)     
        {
            lock (_commands)
            {
                future.Session = this;
                int command = _commandsOut;
                lock (_results)
                {
                    _results.Add(command, future);
                }
                Invoke(m);
            }
            return future;
        }


        public void MessageTransfer(String destination,
                                    MessageAcceptMode acceptMode,
                                    MessageAcquireMode acquireMode,
                                    Header header,
                                    byte[] body,
                                    params Option[] options)
        {
            MemoryStream mbody = new MemoryStream();
            mbody.Write(body,0, body.Length);
            MessageTransfer(destination, acceptMode, acquireMode, header,
                            mbody, options);
        }

        public void MessageTransfer(String destination,
                                    MessageAcceptMode acceptMode,
                                    MessageAcquireMode acquireMode,
                                    Header header,
                                    String body,
                                    params Option[] options)
        {
            MessageTransfer(destination, acceptMode, acquireMode, header,
                            new MemoryStream(Convert.ToByte(body)), options);
        }

        public void Close()
        {
            SessionRequestTimeout(0);
            SessionDetach(_name);
            lock (_commands)
            {
                DateTime start = DateTime.Now;
                long elapsed = 0;

                while (!IsClosed && elapsed < _timeout)
                {
                    Monitor.Wait(_commands, (int) (_timeout - elapsed));
                    elapsed = DateTime.Now.Subtract(start).Milliseconds;
                }
            }
        }

        public void Exception(Exception t)
        {
            log.Error(t, "Caught exception");
        }

        public void Closed()
        {
            IsClosed = true;
            lock (_commands)
            {
                Monitor.PulseAll(_commands);
            }
            lock (_results)
            {
                foreach (IFuture result in _results.Values)
                {
                    lock (result)
                    {
                        Monitor.PulseAll(result);
                    }
                }
            }
            _channel.Session = null;
            _channel = null;
        }

        public override String ToString()
        {
            return String.Format("session:{0}", _name);
        }
    }
}