-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathARTRealtimeChannel.m
1101 lines (968 loc) · 40.3 KB
/
ARTRealtimeChannel.m
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
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// ARTRealtimeChannel.m
// ably
//
// Created by Ricardo Pereira on 30/09/2015.
// Copyright (c) 2015 Ably. All rights reserved.
//
#import "ARTRealtimeChannel+Private.h"
#import "ARTChannel+Private.h"
#import "ARTDataQuery+Private.h"
#import "ARTRealtime+Private.h"
#import "ARTMessage.h"
#import "ARTBaseMessage+Private.h"
#import "ARTAuth.h"
#import "ARTRealtimePresence+Private.h"
#import "ARTChannel.h"
#import "ARTChannelOptions.h"
#import "ARTProtocolMessage.h"
#import "ARTProtocolMessage+Private.h"
#import "ARTPresenceMap.h"
#import "ARTQueuedMessage.h"
#import "ARTNSArray+ARTFunctional.h"
#import "ARTStatus.h"
#import "ARTDefault.h"
#import "ARTRest.h"
#import "ARTClientOptions.h"
#import "ARTTypes.h"
#import "ARTGCD.h"
#import "ARTConnection+Private.h"
#import "ARTRestChannels+Private.h"
#import "ARTEventEmitter+Private.h"
@interface ARTRealtimeChannel () {
ARTRealtimePresence *_realtimePresence;
CFRunLoopTimerRef _attachTimer;
CFRunLoopTimerRef _detachTimer;
__GENERIC(ARTEventEmitter, ARTEvent *, ARTErrorInfo *) *_attachedEventEmitter;
__GENERIC(ARTEventEmitter, ARTEvent *, ARTErrorInfo *) *_detachedEventEmitter;
}
@end
@implementation ARTRealtimeChannel {
dispatch_queue_t _queue;
dispatch_queue_t _userQueue;
ARTErrorInfo *_errorReason;
}
- (instancetype)initWithRealtime:(ARTRealtime *)realtime andName:(NSString *)name withOptions:(ARTChannelOptions *)options {
ART_TRY_OR_MOVE_TO_FAILED_START(realtime) {
self = [super initWithName:name andOptions:options rest:realtime.rest];
if (self) {
_realtime = realtime;
_queue = realtime.rest.queue;
_userQueue = realtime.rest.userQueue;
_restChannel = [_realtime.rest.channels _getChannel:self.name options:options addPrefix:true];
_state = ARTRealtimeChannelInitialized;
_queuedMessages = [NSMutableArray array];
_attachSerial = nil;
_presenceMap = [[ARTPresenceMap alloc] initWithQueue:_queue logger:self.logger];
_presenceMap.delegate = self;
_lastPresenceAction = ARTPresenceAbsent;
_statesEventEmitter = [[ARTPublicEventEmitter alloc] initWithRest:_realtime.rest];
_messagesEventEmitter = [[ARTInternalEventEmitter alloc] initWithQueue:_queue];
_presenceEventEmitter = [[ARTInternalEventEmitter alloc] initWithQueue:_queue];
_attachedEventEmitter = [[ARTInternalEventEmitter alloc] initWithQueue:_queue];
_detachedEventEmitter = [[ARTInternalEventEmitter alloc] initWithQueue:_queue];
_internalEventEmitter = [[ARTInternalEventEmitter alloc] initWithQueue:_queue];
}
return self;
} ART_TRY_OR_MOVE_TO_FAILED_END
}
+ (instancetype)channelWithRealtime:(ARTRealtime *)realtime andName:(NSString *)name withOptions:(ARTChannelOptions *)options {
ART_TRY_OR_MOVE_TO_FAILED_START(realtime) {
return [[ARTRealtimeChannel alloc] initWithRealtime:realtime andName:name withOptions:options];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (ARTRealtimeChannelState)state {
__block ARTRealtimeChannelState ret;
dispatch_sync(_queue, ^{
ret = [self state_nosync];
});
return ret;
}
- (ARTErrorInfo *)errorReason {
__block ARTErrorInfo * ret;
dispatch_sync(_queue, ^{
ret = [self errorReason_nosync];
});
return ret;
}
- (ARTRealtimeChannelState)state_nosync {
return _state;
}
- (ARTErrorInfo *)errorReason_nosync {
return _errorReason;
}
- (ARTLog *)getLogger {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
return _realtime.logger;
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (ARTRealtimePresence *)getPresence {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
if (!_realtimePresence) {
_realtimePresence = [[ARTRealtimePresence alloc] initWithChannel:self];
}
return _realtimePresence;
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)internalPostMessages:(id)data callback:(void (^)(ARTErrorInfo *__art_nullable error))callback {
if (callback) {
void (^userCallback)(ARTErrorInfo *__art_nullable error) = callback;
callback = ^(ARTErrorInfo *__art_nullable error) {
ART_EXITING_ABLY_CODE(_realtime.rest);
dispatch_async(_userQueue, ^{
userCallback(error);
});
};
}
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
ARTProtocolMessage *msg = [[ARTProtocolMessage alloc] init];
msg.action = ARTProtocolMessageMessage;
msg.channel = self.name;
if (![data isKindOfClass:[NSArray class]]) {
data = @[data];
}
msg.messages = data;
[self publishProtocolMessage:msg callback:^void(ARTStatus *status) {
if (callback) callback(status.errorInfo);
}];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)requestContinueSync {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
[self.logger debug:__FILE__ line:__LINE__ message:@"R:%p C:%p ARTRealtime requesting to continue sync operation after reconnect", _realtime, self];
ARTProtocolMessage * msg = [[ARTProtocolMessage alloc] init];
msg.action = ARTProtocolMessageSync;
msg.msgSerial = [NSNumber numberWithLongLong:self.presenceMap.syncMsgSerial];
msg.channelSerial = self.presenceMap.syncChannelSerial;
msg.channel = self.name;
[self.realtime send:msg callback:^(ARTStatus *status) {}];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)publishPresence:(ARTPresenceMessage *)msg callback:(art_nullable void (^)(ARTErrorInfo *__art_nullable))cb {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
switch (_realtime.connection.state_nosync) {
case ARTRealtimeConnected:
break;
case ARTRealtimeConnecting:
case ARTRealtimeDisconnected:
if (_realtime.options.queueMessages) {
break;
}
default:
if (cb) cb([ARTErrorInfo createWithCode:ARTStateBadConnectionState message:@"attempted to publish presence message in a bad connection state"]);
return;
}
if (!msg.clientId && !_realtime.auth.clientId_nosync) {
if (cb) cb([ARTErrorInfo createWithCode:ARTStateNoClientId message:@"attempted to publish presence message without clientId"]);
return;
}
_lastPresenceAction = msg.action;
if (msg.data && self.dataEncoder) {
ARTDataEncoderOutput *encoded = [self.dataEncoder encode:msg.data];
if (encoded.errorInfo) {
[self.logger warn:@"R:%p C:%p error encoding presence message: %@", _realtime, self, encoded.errorInfo];
}
msg.data = encoded.data;
msg.encoding = encoded.encoding;
}
ARTProtocolMessage *pm = [[ARTProtocolMessage alloc] init];
pm.action = ARTProtocolMessagePresence;
pm.channel = self.name;
pm.presence = @[msg];
[self publishProtocolMessage:pm callback:^void(ARTStatus *status) {
if (cb) cb(status.errorInfo);
}];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)publishProtocolMessage:(ARTProtocolMessage *)pm callback:(void (^)(ARTStatus *))cb {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
__weak __typeof(self) weakSelf = self;
ARTStatus *statusInvalidChannel = [ARTStatus state:ARTStateError info:[ARTErrorInfo createWithCode:90001 message:@"channel operation failed (invalid channel state)"]];
switch (_realtime.connection.state_nosync) {
case ARTRealtimeClosing:
case ARTRealtimeClosed: {
if (cb) {
cb(statusInvalidChannel);
}
return;
}
default:
break;
}
void (^queuedCallback)(ARTStatus *) = ^(ARTStatus *status) {
switch (weakSelf.state_nosync) {
case ARTRealtimeChannelDetaching:
case ARTRealtimeChannelDetached:
case ARTRealtimeChannelFailed:
if (cb) {
cb(status.state == ARTStateOk ? statusInvalidChannel : status);
}
return;
default:
break;
}
if (cb) {
cb(status);
}
};
switch (self.state_nosync) {
case ARTRealtimeChannelInitialized:
[self addToQueue:pm callback:queuedCallback];
[self _attach:nil];
break;
case ARTRealtimeChannelAttaching:
[self addToQueue:pm callback:queuedCallback];
break;
case ARTRealtimeChannelSuspended:
case ARTRealtimeChannelDetaching:
case ARTRealtimeChannelDetached:
case ARTRealtimeChannelFailed:
{
if (cb) {
cb(statusInvalidChannel);
}
break;
}
case ARTRealtimeChannelAttached:
{
if (_realtime.connection.state_nosync == ARTRealtimeConnected) {
[self sendMessage:pm callback:cb];
} else {
[self addToQueue:pm callback:queuedCallback];
[self.realtime.internalEventEmitter once:[ARTEvent newWithConnectionEvent:ARTRealtimeConnectionEventConnected] callback:^(ARTConnectionStateChange *__art_nullable change) {
[weakSelf sendQueuedMessages];
}];
}
break;
}
}
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)addToQueue:(ARTProtocolMessage *)msg callback:(void (^)(ARTStatus *))cb {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
BOOL merged = NO;
for (ARTQueuedMessage *queuedMsg in self.queuedMessages) {
merged = [queuedMsg mergeFrom:msg callback:cb];
if (merged) {
break;
}
}
if (!merged) {
ARTQueuedMessage *qm = [[ARTQueuedMessage alloc] initWithProtocolMessage:msg callback:cb];
[self.queuedMessages addObject:qm];
}
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)sendMessage:(ARTProtocolMessage *)pm callback:(void (^)(ARTStatus *))cb {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
NSString *oldConnectionId = self.realtime.connection.id_nosync;
ARTProtocolMessage *pmSent = (ARTProtocolMessage *)[pm copy];
__block BOOL connectionStateHasChanged = false;
__block ARTEventListener *listener = [self.realtime.internalEventEmitter on:^(ARTConnectionStateChange *stateChange) {
if (!(stateChange.current == ARTRealtimeClosed ||
stateChange.current == ARTRealtimeFailed ||
(stateChange.current == ARTRealtimeConnected && ![oldConnectionId isEqual:self.realtime.connection.id_nosync] /* connection state lost */))) {
// Ok
return;
}
connectionStateHasChanged = true;
[self.realtime.internalEventEmitter off:listener];
if (!cb) return;
if (stateChange.current == ARTRealtimeClosed && stateChange.reason == nil && pmSent.action == ARTProtocolMessageClose) {
// No ack/nack is expected.
cb([ARTStatus state:ARTStateOk]);
return;
}
ARTErrorInfo *reason = stateChange.reason ? stateChange.reason : [ARTErrorInfo createWithCode:0 message:@"connection broken before receiving publishing acknowledgement."];
cb([ARTStatus state:ARTStateError info:reason]);
}];
for (ARTMessage *msg in pm.messages) {
msg.connectionId = _realtime.connection.id_nosync;
}
[self.realtime send:pm callback:^(ARTStatus *status) {
// New state change can occur before receiving publishing acknowledgement.
[self.realtime.internalEventEmitter off:listener];
if (cb && !connectionStateHasChanged) cb(status);
}];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (ARTPresenceMap *)presenceMap {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
return _presenceMap;
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)throwOnDisconnectedOrFailed {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
if (self.realtime.connection.state_nosync == ARTRealtimeFailed || self.realtime.connection.state_nosync == ARTRealtimeDisconnected) {
[ARTException raise:@"realtime cannot perform action in disconnected or failed state" format:@"state: %d", (int)self.realtime.connection.state_nosync];
}
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (ARTEventListener *)subscribe:(void (^)(ARTMessage * _Nonnull))callback {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
return [self subscribeWithAttachCallback:nil callback:callback];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (ARTEventListener *)subscribeWithAttachCallback:(void (^)(ARTErrorInfo * _Nullable))onAttach callback:(void (^)(ARTMessage * _Nonnull))cb {
if (cb) {
void (^userCallback)(ARTMessage *__art_nullable m) = cb;
cb = ^(ARTMessage *__art_nullable m) {
ART_EXITING_ABLY_CODE(_realtime.rest);
dispatch_async(_userQueue, ^{
userCallback(m);
});
};
}
if (onAttach) {
void (^userOnAttach)(ARTErrorInfo *__art_nullable m) = onAttach;
onAttach = ^(ARTErrorInfo *__art_nullable m) {
ART_EXITING_ABLY_CODE(_realtime.rest);
dispatch_async(_userQueue, ^{
userOnAttach(m);
});
};
}
__block ARTEventListener *listener = nil;
dispatch_sync(_queue, ^{
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
if (self.state_nosync == ARTRealtimeChannelFailed) {
if (onAttach) onAttach([ARTErrorInfo createWithCode:0 message:@"attempted to subscribe while channel is in Failed state."]);
return;
}
[self _attach:onAttach];
listener = [self.messagesEventEmitter on:cb];
} ART_TRY_OR_MOVE_TO_FAILED_END
});
return listener;
}
- (ARTEventListener *)subscribe:(NSString *)name callback:(void (^)(ARTMessage * _Nonnull))cb {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
return [self subscribe:name onAttach:nil callback:cb];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (ARTEventListener *)subscribe:(NSString *)name onAttach:(void (^)(ARTErrorInfo * _Nullable))onAttach callback:(void (^)(ARTMessage * _Nonnull))cb {
if (cb) {
void (^userCallback)(ARTMessage *__art_nullable m) = cb;
cb = ^(ARTMessage *__art_nullable m) {
ART_EXITING_ABLY_CODE(_realtime.rest);
dispatch_async(_userQueue, ^{
userCallback(m);
});
};
}
__block ARTEventListener *listener = nil;
dispatch_sync(_queue, ^{
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
if (self.state_nosync == ARTRealtimeChannelFailed) {
if (onAttach) onAttach([ARTErrorInfo createWithCode:0 message:@"attempted to subscribe while channel is in Failed state."]);
return;
}
[self _attach:onAttach];
listener = [self.messagesEventEmitter on:name callback:cb];
} ART_TRY_OR_MOVE_TO_FAILED_END
});
return listener;
}
- (void)unsubscribe {
dispatch_sync(_queue, ^{
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
[self _unsubscribe];
} ART_TRY_OR_MOVE_TO_FAILED_END
});
}
- (void)_unsubscribe {
[self.messagesEventEmitter off];
}
- (void)unsubscribe:(ARTEventListener *)listener {
dispatch_sync(_queue, ^{
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
[self.messagesEventEmitter off:listener];
} ART_TRY_OR_MOVE_TO_FAILED_END
});
}
- (void)unsubscribe:(NSString *)name listener:(ARTEventListener *)listener {
dispatch_sync(_queue, ^{
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
[self.messagesEventEmitter off:name listener:listener];
} ART_TRY_OR_MOVE_TO_FAILED_END
});
}
- (ARTEventListener *)on:(ARTChannelEvent)event callback:(void (^)(ARTChannelStateChange *))cb {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
return [self.statesEventEmitter on:[ARTEvent newWithChannelEvent:event] callback:cb];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (ARTEventListener *)on:(void (^)(ARTChannelStateChange *))cb {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
return [self.statesEventEmitter on:cb];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (ARTEventListener *)once:(ARTChannelEvent)event callback:(void (^)(ARTChannelStateChange *))cb {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
return [self.statesEventEmitter once:[ARTEvent newWithChannelEvent:event] callback:cb];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (ARTEventListener *)once:(void (^)(ARTChannelStateChange *))cb {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
return [self.statesEventEmitter once:cb];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)off {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
[self.statesEventEmitter off];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)off_nosync {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
[(ARTPublicEventEmitter *)self.statesEventEmitter off_nosync];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)off:(ARTChannelEvent)event listener:listener {
[self.statesEventEmitter off:[ARTEvent newWithChannelEvent:event] listener:listener];
}
- (void)off:(ARTEventListener *)listener {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
[self.statesEventEmitter off:listener];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)emit:(ARTChannelEvent)event with:(ARTChannelStateChange *)data {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
[self.statesEventEmitter emit:[ARTEvent newWithChannelEvent:event] with:data];
[self.internalEventEmitter emit:[ARTEvent newWithChannelEvent:event] with:data];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)transition:(ARTRealtimeChannelState)state status:(ARTStatus *)status {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
[self.logger debug:__FILE__ line:__LINE__ message:@"channel state transitions to %tu - %@", state, ARTRealtimeChannelStateToStr(state)];
ARTChannelStateChange *stateChange = [[ARTChannelStateChange alloc] initWithCurrent:state previous:self.state_nosync event:(ARTChannelEvent)state reason:status.errorInfo];
self.state = state;
if (status.storeErrorInfo) {
_errorReason = status.errorInfo;
}
switch (state) {
case ARTRealtimeChannelSuspended:
[_attachedEventEmitter emit:nil with:status.errorInfo];
break;
case ARTRealtimeChannelDetached:
[self.presenceMap failsSync:status.errorInfo];
break;
case ARTRealtimeChannelFailed:
[_attachedEventEmitter emit:nil with:status.errorInfo];
[_detachedEventEmitter emit:nil with:status.errorInfo];
[self.presenceMap failsSync:status.errorInfo];
break;
default:
break;
}
[self emit:stateChange.event with:stateChange];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (ARTEventListener *)unlessStateChangesBefore:(NSTimeInterval)deadline do:(void(^)())callback {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
return [[self.internalEventEmitter once:^(ARTChannelStateChange *stateChange) {
// Any state change cancels the timeout.
}] setTimer:deadline onTimeout:^{
if (callback) {
callback();
}
}];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
/**
Checks that a channelSerial is the final serial in a sequence of sync messages,
by checking that there is nothing after the colon
*/
- (bool)isLastChannelSerial:(NSString *)channelSerial {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
NSArray * a = [channelSerial componentsSeparatedByString:@":"];
if([a count] >1 && ![[a objectAtIndex:1] isEqualToString:@""] ) {
return false;
}
return true;
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)onChannelMessage:(ARTProtocolMessage *)message {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
[self.logger debug:__FILE__ line:__LINE__ message:@"R:%p C:%p received channel message %tu - %@", _realtime, self, message.action, ARTProtocolMessageActionToStr(message.action)];
switch (message.action) {
case ARTProtocolMessageAttached:
[self setAttached:message];
break;
case ARTProtocolMessageDetach:
case ARTProtocolMessageDetached:
[self setDetached:message];
break;
case ARTProtocolMessageMessage:
[self onMessage:message];
break;
case ARTProtocolMessagePresence:
[self onPresence:message];
break;
case ARTProtocolMessageError:
[self onError:message];
break;
case ARTProtocolMessageSync:
[self onSync:message];
break;
default:
[self.logger warn:@"R:%p C:%p ARTRealtime, unknown ARTProtocolMessage action: %tu", _realtime, self, message.action];
break;
}
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)setAttached:(ARTProtocolMessage *)message {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
switch (self.state_nosync) {
case ARTRealtimeChannelDetaching:
case ARTRealtimeChannelFailed:
// Ignore
return;
default:
break;
}
self.attachSerial = message.channelSerial;
if (message.hasPresence) {
[self.presenceMap startSync];
[self.logger debug:__FILE__ line:__LINE__ message:@"R:%p C:%p PresenceMap Sync started", _realtime, self];
}
else if ([self.presenceMap.members count] > 0 || [self.presenceMap.localMembers count] > 0) {
if (!message.resumed) {
// When an ATTACHED message is received without a HAS_PRESENCE flag and PresenceMap has existing members
[self.presenceMap startSync];
[self.presenceMap endSync];
}
}
if (self.state_nosync == ARTRealtimeChannelAttached) {
if (message.error != nil) {
_errorReason = message.error;
}
ARTChannelStateChange *stateChange = [[ARTChannelStateChange alloc] initWithCurrent:self.state_nosync previous:self.state_nosync event:ARTChannelEventUpdate reason:message.error resumed:message.resumed];
[self emit:stateChange.event with:stateChange];
return;
}
[self sendQueuedMessages];
ARTStatus *status = message.error ? [ARTStatus state:ARTStateError info:message.error] : [ARTStatus state:ARTStateOk];
[self transition:ARTRealtimeChannelAttached status:status];
[_attachedEventEmitter emit:nil with:nil];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)setDetached:(ARTProtocolMessage *)message {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
switch (self.state_nosync) {
case ARTRealtimeChannelAttached:
case ARTRealtimeChannelSuspended:
[self.realtime.logger debug:__FILE__ line:__LINE__ message:@"R:%p C:%p reattach initiated by DETACHED message", _realtime, self];
[self reattachWithReason:message.error callback:nil];
return;
case ARTRealtimeChannelAttaching: {
[self.realtime.logger debug:__FILE__ line:__LINE__ message:@"R:%p C:%p reattach initiated by DETACHED message but it is currently attaching", _realtime, self];
ARTStatus *status = message.error ? [ARTStatus state:ARTStateError info:message.error] : [ARTStatus state:ARTStateOk];
status.storeErrorInfo = false;
[self setSuspended:status retryIn:_realtime.options.channelRetryTimeout];
return;
}
case ARTRealtimeChannelFailed:
return;
default:
break;
}
self.attachSerial = nil;
ARTErrorInfo *errorInfo = message.error ? message.error : [ARTErrorInfo createWithCode:0 message:@"channel has detached"];
ARTStatus *reason = [ARTStatus state:ARTStateNotAttached info:errorInfo];
[self detachChannel:reason];
[_detachedEventEmitter emit:nil with:nil];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)detachChannel:(ARTStatus *)status {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
[self failQueuedMessages:status];
[self transition:ARTRealtimeChannelDetached status:status];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)setFailed:(ARTStatus *)status {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
[self failQueuedMessages:status];
[self transition:ARTRealtimeChannelFailed status:status];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)setSuspended:(ARTStatus *)status {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
[self setSuspended:status retryIn:self.realtime.options.channelRetryTimeout];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)setSuspended:(ARTStatus *)status retryIn:(NSTimeInterval)retryTimeout {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
[self failQueuedMessages:status];
[self transition:ARTRealtimeChannelSuspended status:status];
__weak __typeof(self) weakSelf = self;
[[self unlessStateChangesBefore:retryTimeout do:^{
[weakSelf reattachWithReason:nil callback:^(ARTErrorInfo *errorInfo) {
ARTStatus *status = [ARTStatus state:ARTStateError info:errorInfo];
[weakSelf setSuspended:status];
}];
}] startTimer];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)onMessage:(ARTProtocolMessage *)message {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
int i = 0;
ARTDataEncoder *dataEncoder = self.dataEncoder;
for (ARTMessage *m in message.messages) {
ARTMessage *msg = m;
if (msg.data && dataEncoder) {
NSError *error = nil;
msg = [msg decodeWithEncoder:dataEncoder error:&error];
if (error != nil) {
ARTErrorInfo *errorInfo = [ARTErrorInfo wrap:[ARTErrorInfo createFromNSError:error] prepend:@"Failed to decode data: "];
[self.logger error:@"R:%p C:%p %@", _realtime, self, errorInfo.message];
_errorReason = errorInfo;
ARTChannelStateChange *stateChange = [[ARTChannelStateChange alloc] initWithCurrent:self.state_nosync previous:self.state_nosync event:ARTChannelEventUpdate reason:errorInfo];
[self emit:stateChange.event with:stateChange];
}
}
if (!msg.timestamp) {
msg.timestamp = message.timestamp;
}
if (!msg.id) {
msg.id = [NSString stringWithFormat:@"%@:%d", message.id, i];
}
[self.messagesEventEmitter emit:msg.name with:msg];
++i;
}
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)onPresence:(ARTProtocolMessage *)message {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
[self.logger debug:__FILE__ line:__LINE__ message:@"handle PRESENCE message"];
int i = 0;
ARTDataEncoder *dataEncoder = self.dataEncoder;
for (ARTPresenceMessage *p in message.presence) {
ARTPresenceMessage *presence = p;
if (presence.data && dataEncoder) {
NSError *error = nil;
presence = [p decodeWithEncoder:dataEncoder error:&error];
if (error != nil) {
ARTErrorInfo *errorInfo = [ARTErrorInfo wrap:[ARTErrorInfo createFromNSError:error] prepend:@"Failed to decode data: "];
[self.logger error:@"R:%p C:%p %@", _realtime, self, errorInfo.message];
}
}
if (!presence.timestamp) {
presence.timestamp = message.timestamp;
}
if (!presence.id) {
presence.id = [NSString stringWithFormat:@"%@:%d", message.id, i];
}
if ([self.presenceMap add:presence]) {
[self broadcastPresence:presence];
}
++i;
}
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)onSync:(ARTProtocolMessage *)message {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
self.presenceMap.syncMsgSerial = [message.msgSerial longLongValue];
self.presenceMap.syncChannelSerial = message.channelSerial;
if (!self.presenceMap.syncInProgress) {
[self.presenceMap startSync];
}
for (int i=0; i<[message.presence count]; i++) {
ARTPresenceMessage *presence = [message.presence objectAtIndex:i];
if ([self.presenceMap add:presence]) {
[self broadcastPresence:presence];
}
}
if ([self isLastChannelSerial:message.channelSerial]) {
[self.presenceMap endSync];
[self.logger debug:__FILE__ line:__LINE__ message:@"R:%p C:%p PresenceMap Sync ended", _realtime, self];
}
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)broadcastPresence:(ARTPresenceMessage *)pm {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
[self.presenceEventEmitter emit:[ARTEvent newWithPresenceAction:pm.action] with:pm];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)onError:(ARTProtocolMessage *)msg {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
[self transition:ARTRealtimeChannelFailed status:[ARTStatus state:ARTStateError info:msg.error]];
[self failQueuedMessages:[ARTStatus state:ARTStateError info: msg.error]];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)attach {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
[self attach:nil];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)attach:(void (^)(ARTErrorInfo *))callback {
if (callback) {
void (^userCallback)(ARTErrorInfo *__art_nullable error) = callback;
callback = ^(ARTErrorInfo *__art_nullable error) {
ART_EXITING_ABLY_CODE(_realtime.rest);
dispatch_async(_userQueue, ^{
userCallback(error);
});
};
}
dispatch_sync(_queue, ^{
[self _attach:callback];
});
}
- (void)_attach:(void (^)(ARTErrorInfo *__art_nullable))callback {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
switch (self.state_nosync) {
case ARTRealtimeChannelAttaching:
[self.realtime.logger verbose:__FILE__ line:__LINE__ message:@"R:%p C:%p already attaching", _realtime, self];
if (callback) [_attachedEventEmitter once:callback];
return;
case ARTRealtimeChannelAttached:
[self.realtime.logger verbose:__FILE__ line:__LINE__ message:@"R:%p C:%p already attached", _realtime, self];
if (callback) callback(nil);
return;
default:
break;
}
[self internalAttach:callback withReason:nil];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)reattachWithReason:(ARTErrorInfo *)reason callback:(void (^)(ARTErrorInfo *))callback {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
switch (self.state_nosync) {
case ARTRealtimeChannelAttached:
case ARTRealtimeChannelSuspended:
[self.realtime.logger debug:__FILE__ line:__LINE__ message:@"R:%p C:%p attached or suspended and will reattach", _realtime, self];
break;
case ARTRealtimeChannelAttaching:
[self.realtime.logger debug:__FILE__ line:__LINE__ message:@"R:%p C:%p already attaching", _realtime, self];
if (callback) [_attachedEventEmitter once:callback];
return;
default:
break;
}
[self internalAttach:callback withReason:reason storeErrorInfo:false];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)internalAttach:(void (^)(ARTErrorInfo *))callback withReason:(ARTErrorInfo *)reason {
[self internalAttach:callback withReason:reason storeErrorInfo:false];
}
- (void)internalAttach:(void (^)(ARTErrorInfo *))callback withReason:(ARTErrorInfo *)reason storeErrorInfo:(BOOL)storeErrorInfo {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
switch (self.state_nosync) {
case ARTRealtimeChannelDetaching: {
[self.realtime.logger debug:__FILE__ line:__LINE__ message:@"R:%p C:%p %@", _realtime, self, @"attach after the completion of Detaching"];
[_detachedEventEmitter once:^(ARTErrorInfo *error) {
[self _attach:callback];
}];
return;
}
default:
break;
}
_errorReason = nil;
if (![self.realtime isActive]) {
[self.realtime.logger debug:__FILE__ line:__LINE__ message:@"R:%p C:%p can't attach when not in an active state", _realtime, self];
if (callback) callback([ARTErrorInfo createWithCode:90000 message:@"Can't attach when not in an active state"]);
return;
}
if (callback) [_attachedEventEmitter once:callback];
// Set state: Attaching
ARTStatus *status = reason ? [ARTStatus state:ARTStateError info:reason] : [ARTStatus state:ARTStateOk];
status.storeErrorInfo = storeErrorInfo;
[self transition:ARTRealtimeChannelAttaching status:status];
[self attachAfterChecks:callback];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)attachAfterChecks:(void (^)(ARTErrorInfo * _Nullable))callback {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
ARTProtocolMessage *attachMessage = [[ARTProtocolMessage alloc] init];
attachMessage.action = ARTProtocolMessageAttach;
attachMessage.channel = self.name;
[self.realtime send:attachMessage callback:nil];
__weak typeof(self) weakSelf = self;
[[self unlessStateChangesBefore:[ARTDefault realtimeRequestTimeout] do:^{
// Timeout
ARTErrorInfo *errorInfo = [ARTErrorInfo createWithCode:ARTStateAttachTimedOut message:@"attach timed out"];
ARTStatus *status = [ARTStatus state:ARTStateAttachTimedOut info:errorInfo];
[weakSelf setSuspended:status];
}] startTimer];
if (![self.realtime shouldQueueEvents]) {
ARTEventListener *reconnectedListener = [self.realtime.connectedEventEmitter once:^(NSNull *n) {
// Disconnected and connected while attaching, re-attach.
[self attachAfterChecks:callback];
}];
[_attachedEventEmitter once:^(ARTErrorInfo *err) {
[self.realtime.connectedEventEmitter off:reconnectedListener];
}];
}
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)detach:(void (^)(ARTErrorInfo * _Nullable))callback {
if (callback) {
void (^userCallback)(ARTErrorInfo *__art_nullable error) = callback;
callback = ^(ARTErrorInfo *__art_nullable error) {
ART_EXITING_ABLY_CODE(_realtime.rest);
dispatch_async(_userQueue, ^{
userCallback(error);
});
};
}
dispatch_sync(_queue, ^{
[self _detach:callback];
});
}
- (void)_detach:(void (^)(ARTErrorInfo * _Nullable))callback {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
switch (self.state_nosync) {
case ARTRealtimeChannelInitialized:
[self.realtime.logger debug:__FILE__ line:__LINE__ message:@"R:%p C:%p can't detach when not attached", _realtime, self];
if (callback) callback(nil);
return;
case ARTRealtimeChannelAttaching: {
[self.realtime.logger debug:__FILE__ line:__LINE__ message:@"R:%p C:%p waiting for the completion of the attaching operation", _realtime, self];
[_attachedEventEmitter once:^(ARTErrorInfo *errorInfo) {
if (callback && errorInfo) {
callback(errorInfo);
}
[self _detach:callback];
}];
return;
}
case ARTRealtimeChannelDetaching:
[self.realtime.logger debug:__FILE__ line:__LINE__ message:@"R:%p C:%p already detaching", _realtime, self];
if (callback) [_detachedEventEmitter once:callback];
return;
case ARTRealtimeChannelDetached:
[self.realtime.logger debug:__FILE__ line:__LINE__ message:@"R:%p C:%p already detached", _realtime, self];
if (callback) callback(nil);
return;
case ARTRealtimeChannelSuspended:
[self.realtime.logger debug:__FILE__ line:__LINE__ message:@"R:%p C:%p transitions immediately to the detached", _realtime, self];
[self transition:ARTRealtimeChannelDetached status:[ARTStatus state:ARTStateOk]];
if (callback) callback(nil);
return;
case ARTRealtimeChannelFailed:
[self.realtime.logger debug:__FILE__ line:__LINE__ message:@"R:%p C:%p can't detach when in a failed state", _realtime, self];
if (callback) callback([ARTErrorInfo createWithCode:90000 message:@"can't detach when in a failed state"]);
return;
default:
break;
}
if (![self.realtime isActive]) {
[self.realtime.logger debug:__FILE__ line:__LINE__ message:@"R:%p C:%p can't detach when not in an active state", _realtime, self];
if (callback) callback([ARTErrorInfo createWithCode:90000 message:@"Can't detach when not in an active state"]);
return;
}
if (callback) [_detachedEventEmitter once:callback];
// Set state: Detaching
[self transition:ARTRealtimeChannelDetaching status:[ARTStatus state:ARTStateOk]];
[self detachAfterChecks:callback];
} ART_TRY_OR_MOVE_TO_FAILED_END
}
- (void)detachAfterChecks:(void (^)(ARTErrorInfo * _Nullable))callback {
ART_TRY_OR_MOVE_TO_FAILED_START(_realtime) {
ARTProtocolMessage *detachMessage = [[ARTProtocolMessage alloc] init];
detachMessage.action = ARTProtocolMessageDetach;
detachMessage.channel = self.name;
[self.realtime send:detachMessage callback:nil];
[[self unlessStateChangesBefore:[ARTDefault realtimeRequestTimeout] do:^{
if (!self.realtime) {
return;
}
// Timeout
ARTErrorInfo *errorInfo = [ARTErrorInfo createWithCode:ARTStateDetachTimedOut message:@"detach timed out"];
ARTStatus *status = [ARTStatus state:ARTStateDetachTimedOut info:errorInfo];
[self transition:ARTRealtimeChannelAttached status:status];
[_detachedEventEmitter emit:nil with:errorInfo];
}] startTimer];
if (![self.realtime shouldQueueEvents]) {
ARTEventListener *reconnectedListener = [self.realtime.connectedEventEmitter once:^(NSNull *n) {
// Disconnected and connected while detaching, re-detach.
[self detachAfterChecks:callback];
}];
[_detachedEventEmitter once:^(ARTErrorInfo *err) {
[self.realtime.connectedEventEmitter off:reconnectedListener];
}];
}