forked from Azure/amqpnetlite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConnection.cs
925 lines (823 loc) · 30.4 KB
/
Connection.cs
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
// ------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// Licensed 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
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR
// CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR
// NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------------------------
namespace Amqp
{
using System;
using System.Threading;
using Amqp.Framing;
using Amqp.Sasl;
using Amqp.Types;
/// <summary>
/// The Connection class represents an AMQP connection.
/// </summary>
public partial class Connection : AmqpObject
{
enum State
{
Start,
HeaderSent,
OpenPipe,
HeaderReceived,
HeaderExchanged,
OpenSent,
OpenReceived,
Opened,
CloseReceived,
CloseSent,
OpenClosePipe,
ClosePipe,
End
}
/// <summary>
/// A flag to disable server certificate validation when TLS is used.
/// </summary>
public static bool DisableServerCertValidation;
internal const uint DefaultMaxFrameSize = 256 * 1024;
internal const ushort DefaultMaxSessions = 256;
internal const int DefaultMaxLinksPerSession = 64;
const uint MaxIdleTimeout = 30 * 60 * 1000;
readonly Address address;
readonly OnOpened onOpened;
Session[] localSessions;
Session[] remoteSessions;
ushort channelMax;
State state;
uint maxFrameSize;
uint remoteMaxFrameSize;
ITransport writer;
Pump reader;
HeartBeat heartBeat;
Connection(ushort channelMax, uint maxFrameSize)
{
this.channelMax = channelMax;
this.maxFrameSize = maxFrameSize;
this.remoteMaxFrameSize = uint.MaxValue;
this.localSessions = new Session[1];
this.remoteSessions = new Session[1];
}
/// <summary>
/// Initializes a connection from the address.
/// </summary>
/// <param name="address">The address.</param>
/// <remarks>
/// The connection initialization includes establishing the underlying transport,
/// which typically has blocking network I/O. Depending on the current synchronization
/// context, it may cause deadlock or UI freeze. Please use the ConnectionFactory.CreateAsync
/// method instead.
/// </remarks>
public Connection(Address address)
: this(address, null, null, null)
{
}
/// <summary>
/// Initializes a connection with SASL profile, open and open callback.
/// </summary>
/// <param name="address">The address.</param>
/// <param name="saslProfile">The SASL profile to do authentication (optional). If it is
/// null and address has user info, SASL PLAIN profile is used.</param>
/// <param name="open">The open frame to send (optional). If not null, all mandatory
/// fields must be set. Ensure that other fields are set to desired values.</param>
/// <param name="onOpened">The callback to handle remote open frame (optional).</param>
/// <remarks>
/// The connection initialization includes establishing the underlying transport,
/// which typically has blocking network I/O. Depending on the current synchronization
/// context, it may cause deadlock or UI freeze. Please use the ConnectionFactory.CreateAsync
/// method instead.
/// </remarks>
public Connection(Address address, SaslProfile saslProfile, Open open, OnOpened onOpened)
: this(DefaultMaxSessions, DefaultMaxFrameSize)
{
this.address = address;
this.onOpened = onOpened;
if (open != null)
{
this.maxFrameSize = open.MaxFrameSize;
this.channelMax = open.ChannelMax;
}
else
{
open = new Open()
{
ContainerId = Guid.NewGuid().ToString(),
HostName = this.address.Host,
MaxFrameSize = this.maxFrameSize,
ChannelMax = this.channelMax
};
}
if (open.IdleTimeOut > 0)
{
this.heartBeat = new HeartBeat(this, open.IdleTimeOut);
}
this.Connect(saslProfile, open);
}
object ThisLock
{
get { return this; }
}
#if NETFX || NETFX40 || DOTNET || NETFX_CORE || WINDOWS_STORE || WINDOWS_PHONE
internal Connection(IBufferManager bufferManager, AmqpSettings amqpSettings, Address address,
IAsyncTransport transport, Open open, OnOpened onOpened)
: this((ushort)(amqpSettings.MaxSessionsPerConnection - 1), (uint)amqpSettings.MaxFrameSize)
{
transport.SetConnection(this);
this.BufferManager = bufferManager;
this.MaxLinksPerSession = amqpSettings.MaxLinksPerSession;
this.address = address;
this.onOpened = onOpened;
this.writer = new TransportWriter(transport, this.OnIoException);
// after getting the transport, move state to open pipe before starting the pump
if (open == null)
{
open = new Open()
{
ContainerId = amqpSettings.ContainerId,
HostName = amqpSettings.HostName ?? this.address.Host,
ChannelMax = this.channelMax,
MaxFrameSize = this.maxFrameSize,
IdleTimeOut = (uint)amqpSettings.IdleTimeout
};
}
if (open.IdleTimeOut > 0)
{
this.heartBeat = new HeartBeat(this, open.IdleTimeOut);
}
this.SendHeader();
this.SendOpen(open);
this.state = State.OpenPipe;
}
/// <summary>
/// Gets a factory with default settings.
/// </summary>
public static ConnectionFactory Factory
{
get { return new ConnectionFactory(); }
}
internal IBufferManager BufferManager
{
get;
private set;
}
internal uint MaxFrameSize
{
get { return this.maxFrameSize; }
}
internal int MaxLinksPerSession;
ByteBuffer AllocateBuffer(int size)
{
return this.BufferManager.GetByteBuffer(size);
}
ByteBuffer WrapBuffer(ByteBuffer buffer, int offset, int length)
{
return new WrappedByteBuffer(buffer, offset, length);
}
#else
internal int MaxLinksPerSession = DefaultMaxLinksPerSession;
ByteBuffer AllocateBuffer(int size)
{
return new ByteBuffer(size, true);
}
ByteBuffer WrapBuffer(ByteBuffer buffer, int offset, int length)
{
return new ByteBuffer(buffer.Buffer, offset, length, length);
}
#endif
internal ushort AddSession(Session session)
{
this.ThrowIfClosed("AddSession");
lock (this.ThisLock)
{
int count = this.localSessions.Length;
for (int i = 0; i < count; ++i)
{
if (this.localSessions[i] == null)
{
this.localSessions[i] = session;
return (ushort)i;
}
}
if (count - 1 < this.channelMax)
{
int size = Math.Min(count * 2, this.channelMax + 1);
Session[] expanded = new Session[size];
Array.Copy(this.localSessions, expanded, count);
this.localSessions = expanded;
this.localSessions[count] = session;
return (ushort)count;
}
throw new AmqpException(ErrorCode.NotAllowed,
Fx.Format(SRAmqp.AmqpHandleExceeded, this.channelMax));
}
}
internal void SendCommand(ushort channel, DescribedList command)
{
if (command.Descriptor.Code == Codec.Close.Code || this.state < State.CloseSent)
{
ByteBuffer buffer = this.AllocateBuffer(Frame.CmdBufferSize);
Frame.Encode(buffer, FrameType.Amqp, channel, command);
this.writer.Send(buffer);
if (this.heartBeat != null)
{
this.heartBeat.OnSend();
}
Trace.WriteLine(TraceLevel.Frame, "SEND (ch={0}) {1}", channel, command);
}
}
internal int SendCommand(ushort channel, Transfer transfer, bool first, ByteBuffer payload, int reservedBytes)
{
this.ThrowIfClosed("Send");
ByteBuffer buffer = this.AllocateBuffer(Frame.CmdBufferSize);
Frame.Encode(buffer, FrameType.Amqp, channel, transfer);
int payloadSize = payload.Length;
int frameSize = buffer.Length + payloadSize;
bool more = frameSize > this.remoteMaxFrameSize;
if (more)
{
transfer.More = true;
buffer.Reset();
Frame.Encode(buffer, FrameType.Amqp, channel, transfer);
frameSize = (int)this.remoteMaxFrameSize;
payloadSize = frameSize - buffer.Length;
}
AmqpBitConverter.WriteInt(buffer.Buffer, buffer.Offset, frameSize);
ByteBuffer frameBuffer;
if (first && !more && reservedBytes >= buffer.Length)
{
// optimize for most common case: single-transfer message
frameBuffer = this.WrapBuffer(payload, payload.Offset - buffer.Length, frameSize);
Array.Copy(buffer.Buffer, buffer.Offset, frameBuffer.Buffer, frameBuffer.Offset, buffer.Length);
buffer.ReleaseReference();
}
else
{
AmqpBitConverter.WriteBytes(buffer, payload.Buffer, payload.Offset, payloadSize);
frameBuffer = buffer;
}
payload.Complete(payloadSize);
this.writer.Send(frameBuffer);
Trace.WriteLine(TraceLevel.Frame, "SEND (ch={0}) {1} payload {2}", channel, transfer, payloadSize);
return payloadSize;
}
/// <summary>
/// Closes the connection.
/// </summary>
/// <param name="error"></param>
/// <returns></returns>
protected override bool OnClose(Error error)
{
lock (this.ThisLock)
{
State newState = State.Start;
if (this.state == State.OpenPipe )
{
newState = State.OpenClosePipe;
}
else if (state == State.OpenSent)
{
newState = State.ClosePipe;
}
else if (this.state == State.Opened)
{
newState = State.CloseSent;
}
else if (this.state == State.CloseReceived)
{
newState = State.End;
}
else if (this.state == State.End)
{
return true;
}
else
{
throw new AmqpException(ErrorCode.IllegalState,
Fx.Format(SRAmqp.AmqpIllegalOperationState, "Close", this.state));
}
this.SendClose(error);
this.state = newState;
return this.state == State.End;
}
}
void Connect(SaslProfile saslProfile, Open open)
{
ITransport transport;
#if NETFX
if (WebSocketTransport.MatchScheme(address.Scheme))
{
WebSocketTransport wsTransport = new WebSocketTransport();
wsTransport.ConnectAsync(address, null).ConfigureAwait(false).GetAwaiter().GetResult();
transport = wsTransport;
}
else
#endif
{
TcpTransport tcpTransport = new TcpTransport();
tcpTransport.Connect(this, this.address, DisableServerCertValidation);
transport = tcpTransport;
}
try
{
if (saslProfile != null)
{
transport = saslProfile.Open(this.address.Host, transport);
}
else if (this.address.User != null)
{
transport = new SaslPlainProfile(this.address.User, this.address.Password).Open(this.address.Host, transport);
}
}
catch
{
transport.Close();
throw;
}
this.writer = new Writer(transport);
// after getting the transport, move state to open pipe before starting the pump
this.SendHeader();
this.SendOpen(open);
this.state = State.OpenPipe;
this.reader = new Pump(this, transport);
this.reader.Start();
}
void ThrowIfClosed(string operation)
{
if (this.state >= State.CloseSent)
{
throw new AmqpException(this.Error ??
new Error(ErrorCode.IllegalState)
{
Description = Fx.Format(SRAmqp.AmqpIllegalOperationState, operation, this.state)
});
}
}
void SendHeader()
{
byte[] header = new byte[] { (byte)'A', (byte)'M', (byte)'Q', (byte)'P', 0, 1, 0, 0 };
this.writer.Send(new ByteBuffer(header, 0, header.Length, header.Length));
Trace.WriteLine(TraceLevel.Frame, "SEND AMQP 0 1.0.0");
}
void SendOpen(Open open)
{
this.SendCommand(0, open);
}
void SendClose(Error error)
{
this.SendCommand(0, new Close() { Error = error });
}
void OnOpen(Open open)
{
lock (this.ThisLock)
{
if (this.state == State.OpenSent)
{
this.state = State.Opened;
}
else if (this.state == State.ClosePipe)
{
this.state = State.CloseSent;
}
else
{
throw new AmqpException(ErrorCode.IllegalState,
Fx.Format(SRAmqp.AmqpIllegalOperationState, "OnOpen", this.state));
}
}
if (this.onOpened != null)
{
this.onOpened(this, open);
}
if (open.ChannelMax < this.channelMax)
{
this.channelMax = open.ChannelMax;
}
this.remoteMaxFrameSize = open.MaxFrameSize;
uint idleTimeout = open.IdleTimeOut;
if (idleTimeout > 0 && this.heartBeat == null)
{
this.heartBeat = new HeartBeat(this, 0);
}
if (this.heartBeat != null)
{
this.heartBeat.Start(idleTimeout);
}
}
void OnClose(Close close)
{
lock (this.ThisLock)
{
if (this.state == State.Opened)
{
this.SendClose(null);
}
else if (this.state == State.CloseSent)
{
}
else
{
throw new AmqpException(ErrorCode.IllegalState,
Fx.Format(SRAmqp.AmqpIllegalOperationState, "OnClose", this.state));
}
this.state = State.End;
this.OnEnded(close.Error);
}
}
internal virtual void OnBegin(ushort remoteChannel, Begin begin)
{
this.ValidateChannel(remoteChannel);
lock (this.ThisLock)
{
Session session = this.GetSession(this.localSessions, begin.RemoteChannel);
session.OnBegin(remoteChannel, begin);
int count = this.remoteSessions.Length;
if (count - 1 < remoteChannel)
{
int size = count * 2;
while (size - 1 < remoteChannel)
{
size *= 2;
}
Session[] expanded = new Session[size];
Array.Copy(this.remoteSessions, expanded, count);
this.remoteSessions = expanded;
}
var remoteSession = this.remoteSessions[remoteChannel];
if (remoteSession != null)
{
throw new AmqpException(ErrorCode.HandleInUse,
Fx.Format(SRAmqp.AmqpHandleInUse, remoteChannel, remoteSession.GetType().Name));
}
this.remoteSessions[remoteChannel] = session;
}
}
internal void ValidateChannel(ushort channel)
{
if (channel > this.channelMax)
{
throw new AmqpException(ErrorCode.NotAllowed,
Fx.Format(SRAmqp.AmqpHandleExceeded, this.channelMax + 1));
}
}
void OnEnd(ushort remoteChannel, End end)
{
Session session = this.GetSession(this.remoteSessions, remoteChannel);
if (session.OnEnd(end))
{
lock (this.ThisLock)
{
this.localSessions[session.Channel] = null;
this.remoteSessions[remoteChannel] = null;
}
}
}
void OnSessionCommand(ushort remoteChannel, DescribedList command, ByteBuffer buffer)
{
this.GetSession(this.remoteSessions, remoteChannel).OnCommand(command, buffer);
}
Session GetSession(Session[] sessions, ushort channel)
{
lock (this.ThisLock)
{
Session session = null;
if (channel < sessions.Length)
{
session = sessions[channel];
}
if (session == null)
{
throw new AmqpException(ErrorCode.NotFound,
Fx.Format(SRAmqp.AmqpChannelNotFound, channel));
}
return session;
}
}
internal bool OnHeader(ProtocolHeader header)
{
Trace.WriteLine(TraceLevel.Frame, "RECV AMQP {0}", header);
if (header.Id != 0 || header.Major != 1 || header.Minor != 0 || header.Revision != 0)
{
throw new AmqpException(ErrorCode.NotImplemented,
Fx.Format(SRAmqp.AmqpProtocolMismatch, header, "0 1 0 0"));
}
lock (this.ThisLock)
{
if (this.state == State.OpenPipe)
{
this.state = State.OpenSent;
}
else if (this.state == State.OpenClosePipe)
{
this.state = State.ClosePipe;
}
else
{
throw new AmqpException(ErrorCode.IllegalState,
Fx.Format(SRAmqp.AmqpIllegalOperationState, "OnHeader", this.state));
}
}
return true;
}
internal bool OnFrame(ByteBuffer buffer)
{
bool shouldContinue = true;
try
{
ushort channel;
DescribedList command;
Frame.Decode(buffer, out channel, out command);
if (buffer.Length > 0)
{
Trace.WriteLine(TraceLevel.Frame, "RECV (ch={0}) {1} payload {2}", channel, command, buffer.Length);
}
else
{
Trace.WriteLine(TraceLevel.Frame, "RECV (ch={0}) {1}", channel, command);
}
if (this.heartBeat != null)
{
this.heartBeat.OnReceive();
}
if (command != null)
{
if (command.Descriptor.Code == Codec.Open.Code)
{
this.OnOpen((Open)command);
}
else if (command.Descriptor.Code == Codec.Close.Code)
{
this.OnClose((Close)command);
shouldContinue = false;
}
else if (command.Descriptor.Code == Codec.Begin.Code)
{
this.OnBegin(channel, (Begin)command);
}
else if (command.Descriptor.Code == Codec.End.Code)
{
this.OnEnd(channel, (End)command);
}
else
{
this.OnSessionCommand(channel, command, buffer);
}
}
}
catch (Exception exception)
{
this.OnException(exception);
shouldContinue = false;
}
return shouldContinue;
}
void OnException(Exception exception)
{
Trace.WriteLine(TraceLevel.Error, "Exception occurred: {0}", exception.ToString());
AmqpException amqpException = exception as AmqpException;
Error error = amqpException != null ?
amqpException.Error :
new Error(ErrorCode.InternalError) { Description = exception.Message };
if (this.state < State.CloseSent)
{
// send close and shutdown the transport.
try
{
this.CloseInternal(0, error);
}
catch
{
}
}
this.state = State.End;
this.OnEnded(error);
}
internal void OnIoException(Exception exception)
{
Trace.WriteLine(TraceLevel.Error, "I/O: {0}", exception.ToString());
if (this.state != State.End)
{
this.state = State.End;
this.CloseCalled = true;
Error error = new Error(ErrorCode.ConnectionForced) { Description = exception.Message };
this.OnEnded(error);
}
}
void OnEnded(Error error)
{
this.Error = error;
if (this.heartBeat != null)
{
this.heartBeat.Stop();
}
if (this.writer != null)
{
this.writer.Close();
}
for (int i = 0; i < this.localSessions.Length; i++)
{
var session = this.localSessions[i];
if (session != null)
{
session.Abort(this.Error);
}
}
this.NotifyClosed(this.Error);
}
sealed class HeartBeat
{
readonly Connection connection;
readonly Timer timer;
uint local; // for enforcing heartbeats
uint remote; // for sending heartbeats
DateTime lastSend;
DateTime lastReceive;
public HeartBeat(Connection connection, uint local)
{
this.connection = connection;
this.local = local;
this.timer = new Timer(OnTimer, this, -1, -1);
}
public void Start(uint remote)
{
this.remote = remote / 2;
this.lastSend = DateTime.UtcNow;
this.lastReceive = DateTime.UtcNow;
this.SetTimer();
}
public void Stop()
{
if (this.timer != null)
{
this.timer.Dispose();
}
}
public void OnSend()
{
this.lastSend = DateTime.UtcNow;
}
public void OnReceive()
{
this.lastReceive = DateTime.UtcNow;
}
static void OnTimer(object state)
{
var thisPtr = (HeartBeat)state;
try
{
DateTime now = DateTime.UtcNow;
if (thisPtr.local > 0 &&
GetDueMilliseconds(thisPtr.local, now, thisPtr.lastReceive) == 0)
{
thisPtr.connection.CloseInternal(
0,
new Error(ErrorCode.ConnectionForced)
{
Description = Fx.Format("Connection closed after idle timeout {0} ms", thisPtr.local)
});
return;
}
if (thisPtr.remote > 0 &&
GetDueMilliseconds(thisPtr.remote, now, thisPtr.lastSend) == 0)
{
thisPtr.connection.writer.Send(new ByteBuffer(new byte[] { 0, 0, 0, 8, 2, 0, 0, 0 }, 0, 8, 8));
thisPtr.OnSend();
Trace.WriteLine(TraceLevel.Frame, "SEND (ch=0) empty");
}
}
catch (Exception exception)
{
Trace.WriteLine(TraceLevel.Warning, "{0}:{1}", exception.GetType().Name, exception.Message);
}
finally
{
if (!thisPtr.connection.IsClosed)
{
thisPtr.SetTimer();
}
}
}
static uint GetDueMilliseconds(uint timeout, DateTime now, DateTime last)
{
uint due = uint.MaxValue;
if (timeout > 0)
{
uint elapsed = (uint)((now.Ticks - last.Ticks) / Encoder.TicksPerMillisecond);
due = timeout > elapsed ? timeout - elapsed : 0;
}
return due;
}
void SetTimer()
{
DateTime now = DateTime.UtcNow;
uint localDue = GetDueMilliseconds(this.local, now, this.lastReceive);
uint remoteDue = GetDueMilliseconds(this.remote, now, this.lastSend);
uint due = localDue < remoteDue ? localDue : remoteDue;
Fx.Assert(due < uint.MaxValue, "At least one timeout should be set");
this.timer.Change(due > int.MaxValue ? int.MaxValue : (int)due, -1);
}
}
// Writer and Pump are for synchronous transport created from the constructors
#if NETMF
sealed class Writer : System.Collections.Queue, ITransport
#else
sealed class Writer : System.Collections.Generic.Queue<ByteBuffer>, ITransport
#endif
{
readonly ITransport transport;
public Writer(ITransport transport)
{
this.transport = transport;
}
void ITransport.Send(ByteBuffer buffer)
{
lock (this)
{
this.Enqueue(buffer);
if (this.Count > 1)
{
return;
}
}
while (buffer != null)
{
this.transport.Send(buffer);
lock (this)
{
this.Dequeue();
if (this.Count > 0)
{
#if NETMF
buffer = (ByteBuffer)this.Peek();
#else
buffer = this.Peek();
#endif
}
else
{
buffer = null;
}
}
}
}
int ITransport.Receive(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
void ITransport.Close()
{
this.transport.Close();
}
}
sealed class Pump
{
readonly Connection connection;
readonly ITransport transport;
public Pump(Connection connection, ITransport transport)
{
this.connection = connection;
this.transport = transport;
}
public void Start()
{
Fx.StartThread(this.PumpThread);
}
void PumpThread()
{
try
{
ProtocolHeader header = Reader.ReadHeader(this.transport);
this.connection.OnHeader(header);
}
catch (Exception exception)
{
this.connection.OnIoException(exception);
return;
}
byte[] sizeBuffer = new byte[FixedWidth.UInt];
while (this.connection.state != State.End)
{
try
{
ByteBuffer buffer = Reader.ReadFrameBuffer(this.transport, sizeBuffer, this.connection.maxFrameSize);
this.connection.OnFrame(buffer);
}
catch (Exception exception)
{
this.connection.OnIoException(exception);
}
}
}
}
}
}