-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathZMQ.Protocol.pas
871 lines (757 loc) · 23.8 KB
/
ZMQ.Protocol.pas
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
unit ZMQ.Protocol;
{ Base class for ZeroMQ protocol }
{$I Grijjy.inc}
interface
uses
System.SysUtils,
System.DateUtils,
System.Classes,
System.SyncObjs,
System.Generics.Collections,
PascalZMQ,
ZMQ.Shared;
const
{ The millisecond interval for heartbeats to the broker }
HEARTBEAT_INTERVAL = 2500;
{ The millisecond elapsed expiration time for the broker heartbeat }
HEARTBEAT_EXPIRES = 5000;
{ The millisecond recv timeout while waiting on incoming messages }
POLLING_INTERVAL = 5;
{ The millisecond delay for reconnecting to the broker }
RECONNECT_DELAY = 500;
{ Timeout connect }
TIMEOUT_CONNECT = 5000;
{ Timeout bind }
TIMEOUT_BIND = 5000;
type
TZMQProtocol = class;
{ Polling thread }
TZMQPollThread = class(TThread)
private
FParent: TZMQProtocol;
{ ZeroMQ socket for thread pool PULL }
FSocket: TZSocket;
{ ZeroMQ context of parent PUSH socket }
FContext: TZContext;
protected
procedure DoTerminate; override;
procedure Execute; override;
public
constructor Create(const AParent: TZMQProtocol; const AContext: TZContext);
destructor Destroy; override;
end;
{ Protocol interface }
TZMQProtocol = class(TThread)
private
{ Internal }
FState: TZMQState;
{ ZeroMQ context }
FContext: TZContext;
{ ZeroMQ socket }
FSocket: TZSocket;
{ ZeroMQ socket type }
FSocketType: TZSocketType;
{ Broker IP/Hostname }
FBrokerAddress: String;
{ Broker public key }
FBrokerPublicKey: String;
{ ZeroMQ routing id }
FSelfId: String;
{ Using heartbeats, if applicable }
FHeartbeats: Boolean;
{ Last time a heartbeat was sent to the broker }
FLastHeartbeatSent: TDateTime;
{ Last time a heartbeat was received from the broker }
FLastHeartbeatRecv: TDateTime;
{ Last error generated }
FLastError: Integer;
{ Use ZMQ built in curve encryption }
FCurveZMQ: Boolean;
{ Authentication and certificate }
FCertificate: TZCertificate;
{ Send queue for messages }
FMessageQueue: TQueue<PZMessage>;
FMessageQueueLock: TCriticalSection;
{ Received messages contain reply routing frames }
FExpectReplyRoutingFrames: Boolean;
{ Use thread pool }
FUseThreadPool: Boolean;
{ Polling threads PUSH context }
FPollThreadsContext: TZContext;
{ Polling threads PUSH socket }
FPollThreadsSocket: TZSocket;
{ Polling threads for load balancing }
FPollThreads: array of TZMQPollThread;
[volatile] FMessageId: Integer;
{ Handle exception for a specific poll thread }
procedure HandleException(const APollThread: TZMQPollThread);
private
{ Get thread safe MessageId }
function GetNextMessageId: Integer;
protected
{ Internal bind broker address }
function _Bind: Boolean;
{ This method is called when the connection is established }
procedure DoConnected; virtual;
{ Internal connect to broker }
function _Connect: Boolean;
{ Internal disconnect from broker }
procedure _Disconnect;
{ Internal reconnect to broker }
procedure _Reconnect;
{ This method is called when a heartbeat needs to be sent }
procedure DoHeartbeat; virtual;
{ This method is called when recv is idle, so that the parent can
perform other background tasks while connected }
procedure DoIdle; virtual;
{ This method is called whenever a new message is received. ASentFrom
is provided only when the socket type is ZMQ_ROUTER otherwise it is
NIL. The message can be handled asynchronously or synchronously by calling
the Send() method in response. }
procedure DoRecv(const ACommand: TZMQCommand;
var AMsg: PZMessage; var ASentFrom: PZFrame); virtual;
{ This method is called whenever a new message may need to be unwrapped
because it was originated from by a ZMQ_DEALER socket }
procedure _DoRecv(const ACommand: TZMQCommand;
var AMsg: PZMessage);
{ Receives a message from the socket, timeout or error. Caller is responsible
for calling zmsg_destroy() to destroy AMsg. Recv() failing multiple
times with LastError = ERR_TIMEOUT is an indicator that communications
may have failed and the client should all Connect() to establish
communications again. }
function _Recv(out AMsg: PZMessage): Boolean;
{ Sends any queued messages to the socket
ZeroMQ sockets are not thread safe so we must perform all socket related IO
operations from inside the same thread. To insure that sends that are
generated from multiple threads are serialized and sent by the thread that
owns the socket, we use a queue }
procedure _Send;
{ Helps us capture exceptions }
procedure DoTerminate; override;
{ Run process loop }
procedure Execute; override;
public
constructor Create(const AHeartbeats: Boolean = False;
const AExpectReplyRoutingFrames: Boolean = False;
const AUseThreadPool: Boolean = False;
const APollThreads: Integer = 0);
destructor Destroy; override;
{ This method binds the broker instance to an endpoint. Note that the protocol
uses a single socket for both clients and workers }
function Bind(const ABrokerAddress: String;
ASocketType: TZSocketType = TZSocketType.Router; const ACurveZMQ: Boolean = False): Boolean;
{ Connect to broker
ASocketType could be ZMQ_REQ for synchronous communications
or ZMQ_DEALER for asychronous communications }
function Connect(const ABrokerAddress: String;
const ABrokerPublicKey: String = '';
const ASocketType: TZSocketType = TZSocketType.Dealer): Boolean; virtual;
{ Disconnect }
procedure Disconnect;
{ Send message }
procedure Send(var AMsg: PZMessage); overload;
{ Send message to a specific target with the supplied routing frame.
This method is used by the broker to send messages to a specific worker
or a specific client }
procedure Send(var AMsg: PZMessage; var ARoutingFrame: PZFrame); overload;
{ Last error reported from class }
property LastError: Integer read FLastError;
{ Heartbeats }
property Heartbeats: Boolean read FHeartbeats write FHeartbeats;
{ State }
property State: TZMQState read FState;
{ Routing id }
property SelfId: String read FSelfId;
{ Thread safe message id }
property NextMessageId: Integer read GetNextMessageId;
end;
implementation
{ TZMQProtocol }
constructor TZMQProtocol.Create(const AHeartbeats: Boolean;
const AExpectReplyRoutingFrames: Boolean;
const AUseThreadPool: Boolean;
const APollThreads: Integer);
var
I: Integer;
PollThreads: Integer;
begin
inherited Create;
{ initialize }
FLastError := 0;
FHeartbeats := AHeartbeats;
FExpectReplyRoutingFrames := AExpectReplyRoutingFrames;
FUseThreadPool := AUseThreadPool;
FCurveZMQ := False;
FState := TZMQState.Idle;
FContext := TZContext.Create;
FMessageQueue := TQueue<PZMessage>.Create;
FMessageQueueLock := TCriticalSection.Create;
FMessageId := 0;
{ initialize thread pool }
if FUseThreadPool then
begin
FPollThreadsContext := TZContext.Create;
FPollThreadsSocket := TZSocket.Create(FPollThreadsContext, TZSocketType.Push);
FPollThreadsSocket.Bind('inproc://workers');
if APollThreads = 0 then
PollThreads := CPUCount
else
PollThreads := APollThreads;
if PollThreads < 2 then
PollThreads := 2; { minimum number of workers }
SetLength(FPollThreads, PollThreads);
for I := 0 to Length(FPollThreads) - 1 do
FPollThreads[I] := TZMQPollThread.Create(Self, FPollThreadsContext);
end;
end;
destructor TZMQProtocol.Destroy;
var
I: Integer;
Msg: PZMessage;
begin
inherited;
if FUseThreadPool then
begin
for I := 0 to Length(FPollThreads) - 1 do
begin
FPollThreads[I].Terminate;
FPollThreads[I].Free;
end;
FPollThreadsSocket.Free(FPollThreadsContext);
FreeAndNil(FPollThreadsContext);
end;
FreeAndNil(FContext);
FCertificate.Free;
FMessageQueueLock.Enter;
try
{ Destroy any messages that may have been left in the queue }
if Assigned(FMessageQueue) then
begin
while (FMessageQueue.Count > 0) do
begin
Msg := FMessageQueue.Dequeue;
Msg.Free;
end;
end;
FMessageQueue.Free;
finally
FMessageQueueLock.Leave;
end;
FMessageQueueLock.Free;
end;
{ This method binds the broker instance to an endpoint. Note that the protocol
uses a single socket for both clients and workers }
function TZMQProtocol.Bind(const ABrokerAddress: String;
ASocketType: TZSocketType; const ACurveZMQ: Boolean): Boolean;
var
Start: TDateTime;
begin
FBrokerAddress := ABrokerAddress;
FSocketType := ASocketType;
FCurveZMQ := ACurveZMQ;
FState := TZMQState.Bind;
{ wait for bind to complete }
Start := Now;
while (MilliSecondsBetween(Now, Start) < TIMEOUT_BIND) and
(FState <> TZMQState.Idle) and
(FState <> TZMQState.Connected) do
Sleep(5);
Result := FState = TZMQState.Connected;
end;
{ Internal bind broker address }
function TZMQProtocol._Bind: Boolean;
begin
FSocket := TZSocket.Create(FContext, FSocketType);
if FCurveZMQ then
begin
{ Load our persistent certificate from disk }
if FileExists(ExtractFilePath(ParamStr(0)) + 'cert') then
FCertificate := TZCertificate.Create('cert')
else
begin
{ Create and save the certificate }
FCertificate := TZCertificate.Create;
FCertificate.Save(ExtractFilePath(ParamStr(0)) + 'cert');
LogMessage('Certificate created');
end;
{ Apply certificate to the socket and use full encryption }
FCertificate.Apply(FSocket);
FSocket.IsCurveServer := True;
end;
{ Bind the socket }
Result := (FSocket.Bind(FBrokerAddress{%H-}) <> -1);
if Result then
LogMessage('Broker is active at ' + FBrokerAddress)
else
LogMessage('Error! Unable to start broker at ' + FBrokerAddress);
end;
{ Connect to broker
ASocketType could be ZMQ_REQ for synchronous communications
or ZMQ_DEALER for asychronous communications }
function TZMQProtocol.Connect(const ABrokerAddress: String;
const ABrokerPublicKey: String; const ASocketType: TZSocketType): Boolean;
var
Start: TDateTime;
begin
FBrokerAddress := ABrokerAddress;
FBrokerPublicKey := ABrokerPublicKey;
FSocketType := ASocketType;
FState := TZMQState.Connect;
{ wait for connection to complete }
Start := Now;
while (MilliSecondsBetween(Now, Start) < TIMEOUT_CONNECT) and
(FState <> TZMQState.Idle) and
(FState <> TZMQState.Connected) do
Sleep(5);
Result := FState = TZMQState.Connected;
end;
procedure TZMQProtocol.Disconnect;
begin
_Disconnect;
end;
{ This method is called when the connection is established }
procedure TZMQProtocol.DoConnected;
begin
inherited;
end;
{ Internal connect to broker }
function TZMQProtocol._Connect: Boolean;
begin
{ start by disconnecting, if applicable }
_Disconnect;
{ create socket }
FSocket := TZSocket.Create(FContext, FSocketType);
{ prevent linger of messages after disconnect }
FSocket.Linger := 0;
{ apply the server public certificate and configure it to use full encryption }
if FBrokerPublicKey <> '' then
begin
FCertificate := TZCertificate.Create;
FCertificate.Apply(FSocket);
{ Apply broker public key to the socket }
FSocket.SetCurveServerKey(FBrokerPublicKey{%H-});
end;
{ connect }
LogMessage('Connecting to broker at ' + FBrokerAddress);
Result := FSocket.Connect(FBrokerAddress{%H-});
if Result then
LogMessage('Connected to broker at ' + FBrokerAddress)
else
LogMessage('Error! Unable to connect to broker at ' + FBrokerAddress);
{ initial heartbeat }
if FHeartbeats then
begin
FLastHeartbeatSent := Now;
FLastHeartbeatRecv := Now;
end;
end;
{ Internal disconnect from broker }
procedure TZMQProtocol._Disconnect;
begin
FSocket.Disconnect(FBrokerAddress{%H-});
FSocket.Free(FContext);
FreeAndNil(FCertificate);
end;
{ Internal reconnect to broker }
procedure TZMQProtocol._Reconnect;
begin
Connect(FBrokerAddress, FBrokerPublicKey, FSocketType);
end;
{ This method is called when a heartbeat needs to be sent }
procedure TZMQProtocol.DoHeartbeat;
begin
inherited;
end;
{ This method is called when recv is idle, so that the parent can
perform other background tasks while connected }
procedure TZMQProtocol.DoIdle;
begin
inherited;
end;
{ Send message }
procedure TZMQProtocol.Send(var AMsg: PZMessage);
//var
// Command: TZMQCommand;
begin
if AMsg.FrameCount = 0 then Exit;
// Command := TZMQCommand(AMsg.Frames[0].AsInteger);
if (FSocketType in [TZSocketType.Dealer, TZSocketType.Router])then
{ empty frame, for ZMQ_DEALER emulation }
AMsg.PushEmptyFrame;
// if (Command <> TZMQCommand.ClientMessage) and
// (Command <> TZMQCommand.WorkerMessage) then
// _Log.Send(Self, Command, AMsg);
FMessageQueueLock.Enter;
try
FMessageQueue.Enqueue(AMsg);
finally
FMessageQueueLock.Leave;
end;
{ the zmsg_send will automatically destroy the message, so we need to
prevent the destruction of the object by our own method }
AMsg := nil;
end;
{ Send message to a specific target with the supplied routing frame.
This method is used by the broker to send messages to a specific worker
or a specific client }
procedure TZMQProtocol.Send(var AMsg: PZMessage; var ARoutingFrame: PZFrame);
//var
// Command: TZMQCommand;
begin
if AMsg.FrameCount = 0 then Exit;
// Command := TZMQCommand(AMsg.Frames[0].AsInteger);
if (FSocketType in [TZSocketType.Dealer, TZSocketType.Router]) then
{ empty frame, for ZMQ_DEALER emulation }
AMsg.PushEmptyFrame;
// if (Command <> TZMQCommand.ClientMessage) and
// (Command <> TZMQCommand.WorkerMessage) then
// _Log.Send(Self, ARoutingFrame, Command, AMsg);
AMsg.Push(ARoutingFrame);
FMessageQueueLock.Enter;
try
FMessageQueue.Enqueue(AMsg);
finally
FMessageQueueLock.Leave;
end;
{ the zmsg_send will automatically destroy the message, so we need to
prevent the destruction of the object by our own method }
AMsg := nil;
end;
{ This method is called whenever a new message is received. ASentFrom
is provided only when the socket type is ZMQ_ROUTER otherwise it is
NIL. The message can be handled asynchronously or synchronously by calling
the Send() method in response. }
procedure TZMQProtocol.DoRecv(const ACommand: TZMQCommand;
var AMsg: PZMessage; var ASentFrom: PZFrame);
begin
inherited;
end;
{ This method is called whenever a new message may need to be unwrapped
because it was originated from by a ZMQ_DEALER socket }
procedure TZMQProtocol._DoRecv(const ACommand: TZMQCommand;
var AMsg: PZMessage);
var
SentFrom: PZFrame;
begin
{ for dealer sockets, the message may contain an optional reply
routing frame so we unpack the frame if required. Only service
modules actually include the reply routing frame currently }
if FExpectReplyRoutingFrames then
begin
if (AMsg.FrameCount >= 2) then
begin
SentFrom := AMsg.Unwrap;
try
DoRecv(ACommand, AMsg, SentFrom);
finally
SentFrom.Free;
end;
end;
end
else
begin
SentFrom := nil;
DoRecv(ACommand, AMsg, SentFrom);
end;
end;
{ Receives a message from the socket, timeout or error. Caller is responsible
for calling zmsg_destroy() to destroy AMsg. Recv() failing multiple
times with LastError = ERR_TIMEOUT is an indicator that communications
may have failed and the client should all Connect() to establish
communications again. }
function TZMQProtocol._Recv(out AMsg: PZMessage): Boolean;
begin
Result := False;
{ wait for an item, timeout or error }
{ the poll method for zmq creates a sleep, so it is not necessary to also
do this inside the thread }
case FSocket.Poll(TZSocketPoll.Input, POLLING_INTERVAL) of
TZSocketPollResult.Available:
begin
AMsg := FSocket.Receive;
if (AMsg <> nil) then
Result := True
else
FLastError := ERR_RECV_INTERRUPTED;
end;
TZSocketPollResult.Timeout:
FLastError := ERR_TIMEOUT;
else
FLastError := ERR_POLL_INTERRUPTED;
end;
end;
{ Sends any queued messages to the socket }
procedure TZMQProtocol._Send;
var
Msg: PZMessage;
begin
FMessageQueueLock.Enter;
try
while FMessageQueue.Count > 0 do
begin
Msg := FMessageQueue.Dequeue;
FSocket.Send(Msg);
end;
finally
FMessageQueueLock.Leave;
end;
end;
procedure TZMQProtocol.DoTerminate;
var
E: TObject;
begin
E := FatalException;
if Assigned(E) then
begin
begin
PPointer(@FatalException)^ := nil;
LogMessage(Format('Error! Exception [%s]', [Exception(E).Message]));
end;
end;
inherited;
end;
{ Run process loop }
procedure TZMQProtocol.Execute;
var
Msg: PZMessage;
SentFrom: PZFrame;
Command: TZMQCommand;
begin
{$IFDEF DEBUG}
NameThreadForDebugging('TZMQProtocol');
{$ENDIF}
while not Terminated do
begin
case FState of
TZMQState.Idle: Sleep(5);
TZMQState.Bind:
begin
if _Bind then
begin
FState := TZMQState.Connected;
end
else
FState := TZMQState.Idle;
end;
TZMQState.Connect:
begin
if _Connect then
begin
DoConnected;
FState := TZMQState.Connected;
end
else
FState := TZMQState.Idle;
end;
TZMQState.Connected:
begin
try
if _Recv(Msg) then
begin
try
SentFrom := nil;
if (FSocketType = TZSocketType.Router) and (Msg.FrameCount >= 3) then
begin
{ routing frame for identifying the sender for replies }
SentFrom := Msg.Pop;
try
{ empty frame, for ZMQ_DEALER emulation }
Msg.PopBytes;
Command := Msg.PopEnum<TZMQCommand>;
// if (Command <> TZMQCommand.ClientMessage) and
// (Command <> TZMQCommand.WorkerMessage) then
// _Log.Recv(Self, SentFrom, Command, Msg);
DoRecv(Command, Msg, SentFrom);
finally
SentFrom.Free;
end;
end
else
if (FSocketType = TZSocketType.Dealer) and (Msg.FrameCount >= 2) then
begin
{ empty frame, for ZMQ_DEALER emulation }
Msg.PopBytes;
Command := Msg.PopEnum<TZMQCommand>;
// if (Command <> TZMQCommand.ClientMessage) and
// (Command <> TZMQCommand.WorkerMessage) then
// _Log.Recv(Self, TZMQCommand(Command), Msg);
{ for dealer sockets we handle the internal commands directly }
case Command of
TZMQCommand.Ready: FSelfId := Msg.PopString;
TZMQCommand.Heartbeat: FLastHeartbeatRecv := Now;
TZMQCommand.Disconnect: FState := TZMQState.Disconnect;
else
begin
if FUseThreadPool then
begin
{ add the command back to the message }
Msg.PushEnum<TZMQCommand>(Command);
{ push the message to the PUSH/PULL thread pool }
FPollThreadsSocket.Send(Msg);
end
else
_DoRecv(Command, Msg);
end;
end;
end
else
FLastError := ERR_INVALID_PAYLOAD;
finally
{ zmq automatically destroys messages when they are sent, so if the
message was generated and received internally and is never going
to be sent or forwarded, then we must destroy it ourselves }
Msg.Free;
end;
end
else
begin
if (FLastError = ERR_RECV_INTERRUPTED) then
LogMessage('Error! Recv error')
else
if (FLastError = ERR_POLL_INTERRUPTED) then
begin
LogMessage('Error! Poll interrupted, shutting down');
Terminate;
end
else
if FLastError = ERR_TIMEOUT then
begin
{ do nothing }
end;
end;
except
on e: EZMQError do
begin
LogMessage(Format('Error! Recv exception [%s]', [e.Message]));
end
else
raise;
end;
{ send all pending queued messages }
_Send;
{ are we sending heartbeats internally? }
if FHeartbeats then
begin
{ send heartbeat to broker }
if MillisecondsBetween(Now, FLastHeartbeatSent) > HEARTBEAT_INTERVAL then
begin
DoHeartbeat;
FLastHeartbeatSent := Now;
end;
{ check for broker expired heartbeat }
if MillisecondsBetween(Now, FLastHeartbeatRecv) > HEARTBEAT_EXPIRES then
begin
LogMessage('Error! Disconnected from broker - retrying');
{ attempt to reconnect }
Sleep(RECONNECT_DELAY);
_Reconnect;
end;
end;
{ This method is called when recv is idle, so that the parent can
perform other background tasks while connected }
DoIdle;
end;
TZMQState.Disconnect:
begin
_Disconnect;
FState := TZMQState.Disconnected;
end;
TZMQState.Disconnected:
begin
{ attempt to reconnect }
Sleep(RECONNECT_DELAY);
_Reconnect;
end;
end;
end;
FState := TZMQState.Shutdown;
end;
function TZMQProtocol.GetNextMessageId: Integer;
begin
Result := TInterlocked.Increment(FMessageId);
end;
procedure TZMQProtocol.HandleException(const APollThread: TZMQPollThread);
var
I: Integer;
begin
{ restart the poll thread }
for I := 0 to Length(FPollThreads) - 1 do
if FPollThreads[I] = APollThread then
begin
FPollThreads[I] := TZMQPollThread.Create(Self, FPollThreadsContext);
Break;
end;
end;
{ TZMQPollThread }
constructor TZMQPollThread.Create(const AParent: TZMQProtocol; const AContext: TZContext);
begin
FParent := AParent;
FContext := AContext;
inherited Create;
end;
destructor TZMQPollThread.Destroy;
begin
inherited;
FSocket.Free(FContext);
end;
procedure TZMQPollThread.DoTerminate;
var
E: TObject;
begin
E := FatalException;
if Assigned(E) then
begin
FSocket.Unbind('inproc://workers'); { stop process worker tasks }
FParent.HandleException(Self);
PPointer(@FatalException)^ := nil;
LogMessage(Format('Error! Exception [%s]', [Exception(E).Message]));
end;
inherited;
end;
procedure TZMQPollThread.Execute;
var
Msg: PZMessage;
Command: TZMQCommand;
begin
{$IFDEF DEBUG}
NameThreadForDebugging('TZMQPollThread');
{$ENDIF}
{ connect to parent zmq context to recv tasks }
FSocket := TZSocket.Create(FContext, TZSocketType.Pull);
FSocket.Connect('inproc://workers');
while not Terminated do
begin
{ wait for an item, timeout or error }
{ the poll method for zmq creates a sleep, so it is not necessary to also
do this inside the thread }
case FSocket.Poll(TZSocketPoll.Input, POLLING_INTERVAL) of
TZSocketPollResult.Available:
begin
{ pull from the thread pool socket }
Msg := FSocket.Receive;
if (Msg <> nil) then
begin
try
Command := Msg.PopEnum<TZMQCommand>;
FParent._DoRecv(Command, Msg);
finally
Msg.Free;
end;
end
else
begin
{ recv interrupted }
LogMessage('Error! Recv error');
end;
end;
TZSocketPollResult.Interrupted:
begin
{ poll interrupted }
LogMessage('Error! Poll interrupted, shutting down');
Terminate;
end;
// TZSocketPollResult.Timeout: Do nothing
end;
end;
end;
end.