File: TimedStream.cs

package info (click to toggle)
mysql-connector-net 6.4.3-4
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 6,160 kB
  • ctags: 8,552
  • sloc: cs: 63,689; xml: 7,505; sql: 345; makefile: 50; ansic: 40
file content (299 lines) | stat: -rw-r--r-- 9,086 bytes parent folder | download | duplicates (2)
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
// Copyright (c) 2009 Sun Microsystems, Inc.
//
// MySQL Connector/NET is licensed under the terms of the GPLv2
// <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most 
// MySQL Connectors. There are special exceptions to the terms and 
// conditions of the GPLv2 as it is applied to this software, see the 
// FLOSS License Exception
// <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
//
// This program is free software; you can redistribute it and/or modify 
// it under the terms of the GNU General Public License as published 
// by the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful, but 
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
// for more details.
//
// You should have received a copy of the GNU General Public License along 
// with this program; if not, write to the Free Software Foundation, Inc., 
// 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA

using System;
using System.IO;
using System.Net.Sockets;
using System.Diagnostics;
using MySql.Data.Common;

namespace MySql.Data.MySqlClient
{
    /// <summary>
    /// Stream that supports timeout of IO operations.
    /// This class is used is used to support timeouts for SQL command, where a 
    /// typical operation involves several network reads/writes. 
    /// Timeout here is defined as the accumulated duration of all IO operations.
    /// </summary>
    
    internal class TimedStream : Stream
    {
        Stream baseStream;

        int timeout;
        int lastReadTimeout;
        int lastWriteTimeout;
        LowResolutionStopwatch stopwatch;
        bool isClosed;


        enum IOKind
        {
            Read,
            Write
        };

        /// <summary>
        /// Construct a TimedStream
        /// </summary>
        /// <param name="baseStream"> Undelying stream</param>
        public TimedStream(Stream baseStream)
        {
            this.baseStream = baseStream;
#if !CF
            timeout = baseStream.ReadTimeout;
#else
            timeout = System.Threading.Timeout.Infinite;
#endif
            isClosed = false;
            stopwatch = new LowResolutionStopwatch();
        }


        /// <summary>
        /// Figure out whether it is necessary to reset timeout on stream.
        /// We track the current value of timeout and try to avoid
        /// changing it too often, because setting Read/WriteTimeout property
        /// on network stream maybe a slow operation that involves a system call 
        /// (setsockopt). Therefore, we allow a small difference, and do not 
        /// reset timeout if current value is slightly greater than the requested
        /// one (within 0.1 second).
        /// </summary>

        private bool ShouldResetStreamTimeout(int currentValue, int newValue)
        {
            if (newValue == System.Threading.Timeout.Infinite
                && currentValue != newValue)
                return true;
            if (newValue > currentValue)
                return true;
            if (currentValue>= newValue + 100)
                return true;

            return false;

        }
        private void StartTimer(IOKind op)
        {

            int streamTimeout;

            if (timeout == System.Threading.Timeout.Infinite)
                streamTimeout = System.Threading.Timeout.Infinite;
            else
                streamTimeout = timeout - (int)stopwatch.ElapsedMilliseconds;

            if (op == IOKind.Read)
            {
                if (ShouldResetStreamTimeout(lastReadTimeout, streamTimeout))
                {
#if !CF
                    baseStream.ReadTimeout = streamTimeout;
#endif
                    lastReadTimeout = streamTimeout;
                }
            }
            else
            {
                if (ShouldResetStreamTimeout(lastWriteTimeout, streamTimeout))
                {
#if !CF
                    baseStream.WriteTimeout = streamTimeout;
#endif
                    lastWriteTimeout = streamTimeout;
                }
            }

            if (timeout == System.Threading.Timeout.Infinite)
                return;

            stopwatch.Start();
        }
        private void StopTimer()
        {
            if (timeout == System.Threading.Timeout.Infinite)
                return;

            stopwatch.Stop();

            // Normally, a timeout exception would be thrown  by stream itself, 
            // since we set the read/write timeout  for the stream.  However 
            // there is a gap between  end of IO operation and stopping the 
            // stop watch,  and it makes it possible for timeout to exceed 
            // even after IO completed successfully.
            if (stopwatch.ElapsedMilliseconds > timeout)
            {
                ResetTimeout(System.Threading.Timeout.Infinite);
                throw new TimeoutException("Timeout in IO operation");
            }
        }
        public override bool CanRead
        {
            get { return baseStream.CanRead; }
        }

        public override bool CanSeek
        {
            get { return baseStream.CanSeek; }
        }

        public override bool CanWrite
        {
            get { return baseStream.CanWrite; }
        }

        public override void Flush()
        {
            try
            {
                StartTimer(IOKind.Write);
                baseStream.Flush();
                StopTimer();
            }
            catch (Exception e)
            {
                HandleException(e);
                throw;
            }
        }

        public override long Length
        {
            get { return baseStream.Length; }
        }

        public override long Position
        {
            get
            {
                return baseStream.Position;
            }
            set
            {
                baseStream.Position = value;
            }
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            try
            {
                StartTimer(IOKind.Read);
                int retval = baseStream.Read(buffer, offset, count);
                StopTimer();
                return retval;
            }
            catch (Exception e)
            {
                HandleException(e);
                throw;
            }
        }

        public override int ReadByte()
        {
            try
            {
                StartTimer(IOKind.Read);
                int retval = baseStream.ReadByte();
                StopTimer();
                return retval;
            }
            catch (Exception e)
            {
                HandleException(e);
                throw;
            }
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            return baseStream.Seek(offset, origin);
        }

        public override void SetLength(long value)
        {
            baseStream.SetLength(value);
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            try
            {
                StartTimer(IOKind.Write);
                baseStream.Write(buffer, offset, count);
                StopTimer();
            }
            catch (Exception e)
            {
                HandleException(e);
                throw;
            }
        }

        public override bool CanTimeout
        {
            get { return baseStream.CanTimeout; }
        }

        public override int ReadTimeout
        {
            get { return baseStream.ReadTimeout; }
            set { baseStream.ReadTimeout = value; }
        }
        public override int WriteTimeout
        {
            get { return baseStream.WriteTimeout; }
            set { baseStream.WriteTimeout = value; }
        }

        public override void Close()
        {
            if (isClosed)
                return;
            isClosed = true;
            baseStream.Close();
        }

        public void ResetTimeout(int newTimeout)
        {
            if (newTimeout == System.Threading.Timeout.Infinite || newTimeout == 0)
                timeout = System.Threading.Timeout.Infinite;
            else
                timeout = newTimeout;
            stopwatch.Reset();
        }


        /// <summary>
        /// Common handler for IO exceptions.
        /// Resets timeout to infinity if timeout exception is 
        /// detected and stops the times.
        /// </summary>
        /// <param name="e">original exception</param>
        void HandleException(Exception e)
        {
            stopwatch.Stop();
            ResetTimeout(-1);
        }
    }
}