-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathrealtimechannel.ts
More file actions
1154 lines (1047 loc) · 38.4 KB
/
realtimechannel.ts
File metadata and controls
1154 lines (1047 loc) · 38.4 KB
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
import { actions, channelModes } from '../types/protocolmessagecommon';
import ProtocolMessage, { fromValues as protocolMessageFromValues } from '../types/protocolmessage';
import EventEmitter from '../util/eventemitter';
import * as Utils from '../util/utils';
import Logger from '../util/logger';
import { EncodingDecodingContext, CipherOptions, populateFieldsFromParent } from '../types/basemessage';
import Message, { getMessagesSize, encodeArray as encodeMessagesArray } from '../types/message';
import ChannelStateChange from './channelstatechange';
import ErrorInfo, { PartialErrorInfo } from '../types/errorinfo';
import * as API from '../../../../ably';
import ConnectionManager from '../transport/connectionmanager';
import { StandardCallback } from '../../types/utils';
import BaseRealtime from './baserealtime';
import { ChannelOptions } from '../../types/channel';
import { normaliseChannelOptions } from '../util/defaults';
import { PaginatedResult } from './paginatedresource';
import type { PushChannel } from 'plugins/push';
import type { WirePresenceMessage } from '../types/presencemessage';
import type { RealtimeObject, WireObjectMessage } from 'plugins/liveobjects';
import type RealtimePresence from './realtimepresence';
import type RealtimeAnnotations from './realtimeannotations';
interface RealtimeHistoryParams {
start?: number;
end?: number;
direction?: string;
limit?: number;
untilAttach?: boolean;
from_serial?: string;
}
function validateChannelOptions(options?: API.ChannelOptions) {
if (options && 'params' in options && !Utils.isObject(options.params)) {
return new ErrorInfo('options.params must be an object', 40000, 400);
}
if (options && 'modes' in options) {
if (!Array.isArray(options.modes)) {
return new ErrorInfo('options.modes must be an array', 40000, 400);
}
for (let i = 0; i < options.modes.length; i++) {
const currentMode = options.modes[i];
if (
!currentMode ||
typeof currentMode !== 'string' ||
!channelModes.includes(String.prototype.toUpperCase.call(currentMode))
) {
return new ErrorInfo('Invalid channel mode: ' + currentMode, 40000, 400);
}
}
}
}
class RealtimeChannel extends EventEmitter {
name: string;
channelOptions: ChannelOptions;
client: BaseRealtime;
private _presence: RealtimePresence | null;
private _annotations: RealtimeAnnotations | null = null;
get presence(): RealtimePresence {
if (!this._presence) {
Utils.throwMissingPluginError('RealtimePresence');
}
return this._presence;
}
get annotations(): RealtimeAnnotations {
if (!this._annotations) {
Utils.throwMissingPluginError('Annotations');
}
return this._annotations;
}
connectionManager: ConnectionManager;
state: API.ChannelState;
subscriptions: EventEmitter;
filteredSubscriptions?: Map<API.messageCallback<Message>, Map<API.MessageFilter, API.messageCallback<Message>[]>>;
syncChannelSerial?: string | null;
properties: {
attachSerial: string | null | undefined;
channelSerial: string | null | undefined;
};
errorReason: ErrorInfo | string | null;
_mode = 0;
_attachResume: boolean;
_decodingContext: EncodingDecodingContext;
_lastPayload: {
messageId?: string | null;
protocolMessageChannelSerial?: string | null;
decodeFailureRecoveryInProgress: null | boolean;
};
/**
* Emits an 'attached' event (with no payload) whenever an ATTACHED protocol
* message is received from the server. Used by setOptions (RTL16a) to know
* when the server has confirmed new channel options.
*/
_attachedReceived: EventEmitter;
/**
* Internal event emitter for channel state changes, not affected by public
* off() calls. Exists to satisfy RTC10: the client library should never
* register internal listeners with the public EventEmitter in such a way
* that a user calling off() would result in the library not working as
* expected.
*/
internalStateChanges: EventEmitter;
params?: Record<string, any>;
modes: API.ChannelMode[] | undefined;
stateTimer?: number | NodeJS.Timeout | null;
retryTimer?: number | NodeJS.Timeout | null;
retryCount: number = 0;
_push?: PushChannel;
_object?: RealtimeObject;
constructor(client: BaseRealtime, name: string, options?: API.ChannelOptions) {
super(client.logger);
Logger.logAction(this.logger, Logger.LOG_MINOR, 'RealtimeChannel()', 'started; name = ' + name);
this.name = name;
this.channelOptions = normaliseChannelOptions(client._Crypto ?? null, this.logger, options);
this.client = client;
this._presence = client._RealtimePresence ? new client._RealtimePresence.RealtimePresence(this) : null;
if (client._Annotations) {
this._annotations = new client._Annotations.RealtimeAnnotations(this);
}
this.connectionManager = client.connection.connectionManager;
this.state = 'initialized';
this.subscriptions = new EventEmitter(this.logger);
this.syncChannelSerial = undefined;
this.properties = {
attachSerial: undefined,
channelSerial: undefined,
};
this.setOptions(options);
this.errorReason = null;
this._attachResume = false;
this._decodingContext = {
channelOptions: this.channelOptions,
plugins: client.options.plugins || {},
baseEncodedPreviousPayload: undefined,
};
this._lastPayload = {
messageId: null,
protocolMessageChannelSerial: null,
decodeFailureRecoveryInProgress: null,
};
this._attachedReceived = new EventEmitter(this.logger);
this.internalStateChanges = new EventEmitter(this.logger);
if (client.options.plugins?.Push) {
this._push = new client.options.plugins.Push.PushChannel(this);
}
if (client.options.plugins?.LiveObjects) {
this._object = new client.options.plugins.LiveObjects.RealtimeObject(this);
}
}
get push() {
if (!this._push) {
Utils.throwMissingPluginError('Push');
}
return this._push;
}
/** @spec RTL27 */
get object() {
if (!this._object) {
Utils.throwMissingPluginError('LiveObjects'); // RTL27b
}
return this._object; // RTL27a
}
// Override of EventEmitter method
emit(event: string, ...args: unknown[]) {
super.emit(event, ...args);
this.internalStateChanges.emit(event, ...args);
}
invalidStateError(): ErrorInfo {
return new ErrorInfo(
'Channel operation failed as channel state is ' + this.state,
90001,
400,
this.errorReason || undefined,
);
}
static processListenerArgs(args: unknown[]): any[] {
/* [event], listener */
args = Array.prototype.slice.call(args);
if (typeof args[0] === 'function') {
args.unshift(null);
}
return args;
}
async setOptions(options?: API.ChannelOptions): Promise<void> {
const previousChannelOptions = this.channelOptions;
const err = validateChannelOptions(options);
if (err) {
throw err;
}
this.channelOptions = normaliseChannelOptions(this.client._Crypto ?? null, this.logger, options);
if (this._decodingContext) this._decodingContext.channelOptions = this.channelOptions;
if (this._shouldReattachToSetOptions(options, previousChannelOptions)) {
/* This does not just do _attach(true, null, callback) because that would put us
* into the 'attaching' state until we receive the new attached, which is
* conceptually incorrect: we are still attached, we just have a pending request to
* change some channel params. Per RTL17 going into the attaching state would mean
* rejecting messages until we have confirmation that the options have changed,
* which would unnecessarily lose message continuity. */
this.attachImpl();
return new Promise<void>((resolve, reject) => {
const cleanup = () => {
this._attachedReceived.off(onAttached);
this.internalStateChanges.off(onFailure);
};
const onAttached = () => {
cleanup();
resolve();
};
const onFailure = (stateChange: ChannelStateChange) => {
cleanup();
reject(stateChange.reason);
};
this._attachedReceived.once('attached', onAttached);
this.internalStateChanges.once(['detached', 'failed'], onFailure);
});
}
}
_shouldReattachToSetOptions(options: API.ChannelOptions | undefined, prevOptions: API.ChannelOptions) {
if (!(this.state === 'attached' || this.state === 'attaching')) {
return false;
}
if (options?.params) {
// Don't check against the `agent` param - it isn't returned in the ATTACHED message
const requestedParams = omitAgent(options.params);
const existingParams = omitAgent(prevOptions.params);
if (Object.keys(requestedParams).length !== Object.keys(existingParams).length) {
return true;
}
if (!Utils.shallowEquals(existingParams, requestedParams)) {
return true;
}
}
if (options?.modes) {
if (!prevOptions.modes || !Utils.arrEquals(options.modes, prevOptions.modes)) {
return true;
}
}
return false;
}
async publish(...args: any[]): Promise<API.PublishResult> {
const first = args[0],
second = args[1];
let messages: Message[];
let params: Record<string, any> | undefined;
if (typeof first === 'string' || first === null || first === undefined) {
messages = [Message.fromValues({ name: first, data: second })];
params = args[2];
} else if (Utils.isObject(first)) {
messages = [Message.fromValues(first)];
params = args[1];
} else if (Array.isArray(first)) {
messages = Message.fromValuesArray(first);
params = args[1];
} else {
throw new ErrorInfo(
'The single-argument form of publish() expects a message object or an array of message objects',
40013,
400,
);
}
const maxMessageSize = this.client.options.maxMessageSize;
// TODO get rid of CipherOptions type assertion, indicates channeloptions types are broken
const wireMessages = await encodeMessagesArray(messages, this.channelOptions as CipherOptions);
/* RSL1i */
const size = getMessagesSize(wireMessages);
if (size > maxMessageSize) {
throw new ErrorInfo(
`Maximum size of messages that can be published at once exceeded (was ${size} bytes; limit is ${maxMessageSize} bytes)`,
40009,
400,
);
}
this.throwIfUnpublishableState();
Logger.logAction(
this.logger,
Logger.LOG_MICRO,
'RealtimeChannel.publish()',
'sending message; channel state is ' + this.state + ', message count = ' + wireMessages.length,
);
const pm = protocolMessageFromValues({
action: actions.MESSAGE,
channel: this.name,
messages: wireMessages,
params: params ? Utils.stringifyValues(params) : undefined,
});
return this.sendAndAwaitAck(pm);
}
throwIfUnpublishableState(): void {
if (!this.connectionManager.activeState()) {
throw this.connectionManager.getError();
}
if (this.state === 'failed' || this.state === 'suspended') {
throw this.invalidStateError();
}
}
onEvent(messages: Array<any>): void {
Logger.logAction(this.logger, Logger.LOG_MICRO, 'RealtimeChannel.onEvent()', 'received message');
const subscriptions = this.subscriptions;
for (let i = 0; i < messages.length; i++) {
const message = messages[i];
subscriptions.emit(message.name, message);
}
}
async attach(): Promise<ChannelStateChange | null> {
if (this.state === 'attached') {
return null;
}
return new Promise((resolve, reject) => {
this._attach(false, null, (err, result) => (err ? reject(err) : resolve(result!)));
});
}
_attach(
forceReattach: boolean,
attachReason: ErrorInfo | null,
callback?: StandardCallback<ChannelStateChange>,
): void {
if (!callback) {
callback = (err?: ErrorInfo | null) => {
if (err) {
Logger.logAction(
this.logger,
Logger.LOG_ERROR,
'RealtimeChannel._attach()',
'Channel attach failed: ' + err.toString(),
);
}
};
}
const connectionManager = this.connectionManager;
if (!connectionManager.activeState()) {
callback(connectionManager.getError());
return;
}
if (this.state !== 'attaching' || forceReattach) {
this.requestState('attaching', attachReason);
}
this.internalStateChanges.once(function (this: { event: string }, stateChange: ChannelStateChange) {
switch (this.event) {
case 'attached':
callback?.(null, stateChange);
break;
case 'detached':
case 'suspended':
case 'failed':
callback?.(
stateChange.reason ||
connectionManager.getError() ||
new ErrorInfo('Unable to attach; reason unknown; state = ' + this.event, 90000, 500),
);
break;
case 'detaching':
callback?.(new ErrorInfo('Attach request superseded by a subsequent detach request', 90000, 409));
break;
}
});
}
attachImpl(): void {
Logger.logAction(this.logger, Logger.LOG_MICRO, 'RealtimeChannel.attachImpl()', 'sending ATTACH message');
const attachMsg = protocolMessageFromValues({
action: actions.ATTACH,
channel: this.name,
params: this.channelOptions.params,
// RTL4c1: Includes the channel serial to resume from a previous message
// or attachment.
channelSerial: this.properties.channelSerial,
});
if (this.channelOptions.modes) {
attachMsg.encodeModesToFlags(Utils.allToUpperCase(this.channelOptions.modes) as API.ChannelMode[]);
}
if (this._attachResume) {
attachMsg.setFlag('ATTACH_RESUME');
}
if (this._lastPayload.decodeFailureRecoveryInProgress) {
attachMsg.channelSerial = this._lastPayload.protocolMessageChannelSerial;
}
this.send(attachMsg);
}
async detach(): Promise<void> {
const connectionManager = this.connectionManager;
switch (this.state) {
// RTL5j
case 'suspended':
this.notifyState('detached');
return;
case 'detached':
return;
// RTL5b
case 'failed':
throw new ErrorInfo('Unable to detach; channel state = failed', 90001, 400);
default:
// RTL5l: if connection is not connected, immediately transition to detached
if (connectionManager.state.state !== 'connected') {
this.notifyState('detached');
return;
}
this.requestState('detaching');
// eslint-disable-next-line no-fallthrough
case 'detaching':
return new Promise((resolve, reject) => {
this.internalStateChanges.once(function (this: { event: string }, stateChange: ChannelStateChange) {
switch (this.event) {
case 'detached':
resolve();
break;
case 'attached':
case 'suspended':
case 'failed':
reject(
stateChange.reason ||
connectionManager.getError() ||
new ErrorInfo('Unable to detach; reason unknown; state = ' + this.event, 90000, 500),
);
break;
case 'attaching':
reject(new ErrorInfo('Detach request superseded by a subsequent attach request', 90000, 409));
break;
}
});
});
}
}
detachImpl(): void {
Logger.logAction(this.logger, Logger.LOG_MICRO, 'RealtimeChannel.detach()', 'sending DETACH message');
const msg = protocolMessageFromValues({ action: actions.DETACH, channel: this.name });
this.send(msg);
}
async subscribe(...args: unknown[] /* [event], listener */): Promise<ChannelStateChange | null> {
const [event, listener] = RealtimeChannel.processListenerArgs(args);
if (this.state === 'failed') {
throw ErrorInfo.fromValues(this.invalidStateError());
}
// Filtered
if (event && typeof event === 'object' && !Array.isArray(event)) {
this.client._FilteredSubscriptions.subscribeFilter(this, event, listener);
} else {
this.subscriptions.on(event, listener);
}
// (RTL7g)
if (this.channelOptions.attachOnSubscribe !== false) {
return this.attach();
} else {
return null;
}
}
unsubscribe(...args: unknown[] /* [event], listener */): void {
const [event, listener] = RealtimeChannel.processListenerArgs(args);
// If we either have a filtered listener, a filter or both we need to do additional processing to find the original function(s)
if ((typeof event === 'object' && !listener) || this.filteredSubscriptions?.has(listener)) {
this.client._FilteredSubscriptions
.getAndDeleteFilteredSubscriptions(this, event, listener)
.forEach((l) => this.subscriptions.off(l));
return;
}
this.subscriptions.off(event, listener);
}
sync(): void {
/* check preconditions */
switch (this.state) {
case 'initialized':
case 'detaching':
case 'detached':
throw new PartialErrorInfo('Unable to sync to channel; not attached', 40000);
default:
}
const connectionManager = this.connectionManager;
if (!connectionManager.activeState()) {
throw connectionManager.getError();
}
/* send sync request */
const syncMessage = protocolMessageFromValues({ action: actions.SYNC, channel: this.name });
if (this.syncChannelSerial) {
syncMessage.channelSerial = this.syncChannelSerial;
}
connectionManager.send(syncMessage);
}
send(msg: ProtocolMessage): void {
this.connectionManager.send(msg);
}
async sendAndAwaitAck(msg: ProtocolMessage): Promise<API.PublishResult> {
return new Promise((resolve, reject) => {
this.connectionManager.send(msg, this.client.options.queueMessages, (err, publishResponse) => {
if (err) {
reject(err);
} else {
resolve(publishResponse!);
}
});
});
}
async sendPresence(presence: WirePresenceMessage[]): Promise<void> {
const msg = protocolMessageFromValues({
action: actions.PRESENCE,
channel: this.name,
presence: presence,
});
await this.sendAndAwaitAck(msg);
}
async sendState(objectMessages: WireObjectMessage[]): Promise<API.PublishResult> {
const msg = protocolMessageFromValues({
action: actions.OBJECT,
channel: this.name,
state: objectMessages,
});
return this.sendAndAwaitAck(msg);
}
// Access to this method is synchronised by ConnectionManager#processChannelMessage, in order to synchronise access to the state stored in _decodingContext.
async processMessage(message: ProtocolMessage): Promise<void> {
if (
message.action === actions.ATTACHED ||
message.action === actions.MESSAGE ||
message.action === actions.PRESENCE ||
message.action === actions.OBJECT ||
message.action === actions.ANNOTATION
) {
// RTL15b
this.setChannelSerial(message.channelSerial);
}
let syncChannelSerial,
isSync = false;
switch (message.action) {
case actions.ATTACHED: {
this.properties.attachSerial = message.channelSerial;
this._mode = message.getMode();
this.params = (message as any).params || {};
const modesFromFlags = message.decodeModesFromFlags();
this.modes = (modesFromFlags && (Utils.allToLowerCase(modesFromFlags) as API.ChannelMode[])) || undefined;
const resumed = message.hasFlag('RESUMED');
const hasPresence = message.hasFlag('HAS_PRESENCE');
const hasBacklog = message.hasFlag('HAS_BACKLOG');
const hasObjects = message.hasFlag('HAS_OBJECTS');
this._attachedReceived.emit('attached');
if (this.state === 'attached') {
if (!resumed) {
// we have lost continuity.
// the presence set needs to be re-synced
if (this._presence) {
this._presence.onAttached(hasPresence);
}
// the Objects tree needs to be re-synced
if (this._object) {
this._object.onAttached(hasObjects);
}
}
const change = new ChannelStateChange(this.state, this.state, resumed, hasBacklog, message.error);
if (!resumed || this.channelOptions.updateOnAttached) {
this.emit('update', change);
}
} else if (this.state === 'detaching') {
/* RTL5i: re-send DETACH and remain in the 'detaching' state */
this.checkPendingState();
} else {
this.notifyState('attached', message.error, resumed, hasPresence, hasBacklog, hasObjects);
}
break;
}
case actions.DETACHED: {
const detachErr = message.error
? ErrorInfo.fromValues(message.error)
: new ErrorInfo('Channel detached', 90001, 404);
if (this.state === 'detaching') {
this.notifyState('detached', detachErr);
} else if (this.state === 'attaching') {
/* Only retry immediately if we were previously attached. If we were
* attaching, go into suspended, fail messages, and wait a few seconds
* before retrying */
this.notifyState('suspended', detachErr);
} else if (this.state === 'attached' || this.state === 'suspended') {
// RTL13a
this.requestState('attaching', detachErr);
}
// else no action (detached in initialized, detached, or failed state is a noop)
break;
}
case actions.SYNC:
/* syncs can have channelSerials, but might not if the sync is one page long */
isSync = true;
syncChannelSerial = this.syncChannelSerial = message.channelSerial;
/* syncs can happen on channels with no presence data as part of connection
* resuming, in which case protocol message has no presence property */
if (!message.presence) break;
// eslint-disable-next-line no-fallthrough
case actions.PRESENCE: {
if (!message.presence) {
break;
}
populateFieldsFromParent(message);
const options = this.channelOptions;
if (this._presence) {
const presenceMessages = await Promise.all(
message.presence.map((wpm) => {
return wpm.decode(options, this.logger);
}),
);
this._presence.setPresence(presenceMessages, isSync, syncChannelSerial as any);
}
break;
}
// RTL1
// OBJECT and OBJECT_SYNC message processing share most of the logic, so group them together
case actions.OBJECT:
case actions.OBJECT_SYNC: {
if (!this._object || !message.state) {
return;
}
populateFieldsFromParent(message);
// need to use the active protocol format instead of just client's useBinaryProtocol option,
// as comet transport does not support msgpack and will default to json without changing useBinaryProtocol.
// message processing is done in the same event loop tick up until this point,
// so we can reliably expect an active protocol to exist and be the one that received the object message.
const format = this.client.connection.connectionManager.getActiveTransportFormat()!;
const objectMessages = message.state.map((om) => om.decode(this.client, format));
if (message.action === actions.OBJECT) {
this._object.handleObjectMessages(objectMessages);
} else {
this._object.handleObjectSyncMessages(objectMessages, message.channelSerial);
}
break;
}
case actions.MESSAGE: {
//RTL17
if (this.state !== 'attached') {
Logger.logAction(
this.logger,
Logger.LOG_MAJOR,
'RealtimeChannel.processMessage()',
'Message "' +
message.id +
'" skipped as this channel "' +
this.name +
'" state is not "attached" (state is "' +
this.state +
'").',
);
return;
}
populateFieldsFromParent(message);
const encoded = message.messages!,
firstMessage = encoded[0],
lastMessage = encoded[encoded.length - 1];
if (
firstMessage.extras &&
firstMessage.extras.delta &&
firstMessage.extras.delta.from !== this._lastPayload.messageId
) {
const msg =
'Delta message decode failure - previous message not available for message "' +
message.id +
'" on this channel "' +
this.name +
'".';
Logger.logAction(this.logger, Logger.LOG_ERROR, 'RealtimeChannel.processMessage()', msg);
this._startDecodeFailureRecovery(new ErrorInfo(msg, 40018, 400));
break;
}
let messages: Message[] = [];
for (let i = 0; i < encoded.length; i++) {
const { decoded, err } = await encoded[i].decodeWithErr(this._decodingContext, this.logger);
messages[i] = decoded;
if (err) {
switch (err.code) {
case 40018:
/* decode failure */
this._startDecodeFailureRecovery(err);
return;
case 40019: /* No vcdiff plugin passed in - no point recovering, give up */
case 40021:
/* Browser does not support deltas, similarly no point recovering */
this.notifyState('failed', err);
return;
default:
// do nothing, continue decoding
}
}
}
this._lastPayload.messageId = lastMessage.id;
this._lastPayload.protocolMessageChannelSerial = message.channelSerial;
this.onEvent(messages);
break;
}
case actions.ANNOTATION: {
populateFieldsFromParent(message);
const options = this.channelOptions;
if (this._annotations) {
const annotations = await Promise.all(
(message.annotations || []).map((wpm) => {
return wpm.decode(options, this.logger);
}),
);
this._annotations._processIncoming(annotations);
}
break;
}
case actions.ERROR: {
/* there was a channel-specific error */
const err = message.error as ErrorInfo;
if (err && err.code == 80016) {
/* attach/detach operation attempted on superseded transport handle */
this.checkPendingState();
} else {
this.notifyState('failed', ErrorInfo.fromValues(err));
}
break;
}
default:
// RSF1, should handle unrecognized message actions gracefully and don't abort the realtime connection to ensure forward compatibility
Logger.logAction(
this.logger,
Logger.LOG_MAJOR,
'RealtimeChannel.processMessage()',
'Protocol error: unrecognised message action (' + message.action + ')',
);
}
}
_startDecodeFailureRecovery(reason: ErrorInfo): void {
if (!this._lastPayload.decodeFailureRecoveryInProgress) {
Logger.logAction(
this.logger,
Logger.LOG_MAJOR,
'RealtimeChannel.processMessage()',
'Starting decode failure recovery process.',
);
this._lastPayload.decodeFailureRecoveryInProgress = true;
this._attach(true, reason, () => {
this._lastPayload.decodeFailureRecoveryInProgress = false;
});
}
}
onAttached(): void {
Logger.logAction(
this.logger,
Logger.LOG_MINOR,
'RealtimeChannel.onAttached',
'activating channel; name = ' + this.name,
);
}
notifyState(
state: API.ChannelState,
reason?: ErrorInfo | null,
resumed?: boolean,
hasPresence?: boolean,
hasBacklog?: boolean,
hasObjects?: boolean,
): void {
Logger.logAction(
this.logger,
Logger.LOG_MICRO,
'RealtimeChannel.notifyState',
'name = ' + this.name + ', current state = ' + this.state + ', notifying state ' + state,
);
this.clearStateTimer();
// RTP5a1
if (['detached', 'suspended', 'failed'].includes(state)) {
this.properties.channelSerial = null;
}
if (state === this.state) {
return;
}
if (this._presence) {
this._presence.actOnChannelState(state, hasPresence, reason);
}
if (this._object) {
this._object.actOnChannelState(state, hasObjects);
}
if (state === 'suspended' && this.connectionManager.state.sendEvents) {
this.startRetryTimer();
} else {
this.cancelRetryTimer();
}
if (reason) {
this.errorReason = reason;
}
const change = new ChannelStateChange(this.state, state, resumed, hasBacklog, reason);
const action = 'Channel state for channel "' + this.name + '"';
const message = state + (reason ? '; reason: ' + reason : '');
if (state === 'failed') {
Logger.logAction(this.logger, Logger.LOG_ERROR, action, message);
} else {
Logger.logAction(this.logger, Logger.LOG_MAJOR, action, message);
}
if (state !== 'attaching' && state !== 'suspended') {
this.retryCount = 0;
}
/* Note: we don't set inProgress for pending states until the request is actually in progress */
if (state === 'attached') {
this.onAttached();
}
if (state === 'attached') {
this._attachResume = true;
} else if (state === 'detaching' || state === 'failed') {
this._attachResume = false;
}
this.state = state;
this.emit(state, change);
}
requestState(state: API.ChannelState, reason?: ErrorInfo | null): void {
Logger.logAction(
this.logger,
Logger.LOG_MINOR,
'RealtimeChannel.requestState',
'name = ' + this.name + ', state = ' + state,
);
this.notifyState(state, reason);
/* send the event and await response */
this.checkPendingState();
}
checkPendingState(): void {
/* if can't send events, do nothing */
const cmState = this.connectionManager.state;
if (!cmState.sendEvents) {
Logger.logAction(
this.logger,
Logger.LOG_MINOR,
'RealtimeChannel.checkPendingState',
'sendEvents is false; state is ' + this.connectionManager.state.state,
);
return;
}
Logger.logAction(
this.logger,
Logger.LOG_MINOR,
'RealtimeChannel.checkPendingState',
'name = ' + this.name + ', state = ' + this.state,
);
/* Only start the state timer running when actually sending the event */
switch (this.state) {
case 'attaching':
this.startStateTimerIfNotRunning();
this.attachImpl();
break;
case 'detaching':
this.startStateTimerIfNotRunning();
this.detachImpl();
break;
case 'attached':
/* resume any sync operation that was in progress */
this.sync();
break;
default:
break;
}
}
timeoutPendingState(): void {
switch (this.state) {
case 'attaching': {
const err = new ErrorInfo('Channel attach timed out', 90007, 408);
this.notifyState('suspended', err);
break;
}
case 'detaching': {
const err = new ErrorInfo('Channel detach timed out', 90007, 408);
this.notifyState('attached', err);
break;
}
default:
this.checkPendingState();
break;
}
}
startStateTimerIfNotRunning(): void {
if (!this.stateTimer) {
this.stateTimer = setTimeout(() => {
Logger.logAction(this.logger, Logger.LOG_MINOR, 'RealtimeChannel.startStateTimerIfNotRunning', 'timer expired');
this.stateTimer = null;
this.timeoutPendingState();
}, this.client.options.timeouts.realtimeRequestTimeout);
}
}
clearStateTimer(): void {
const stateTimer = this.stateTimer;
if (stateTimer) {
clearTimeout(stateTimer);
this.stateTimer = null;
}
}
startRetryTimer(): void {
if (this.retryTimer) return;
this.retryCount++;
const retryDelay = Utils.getRetryTime(this.client.options.timeouts.channelRetryTimeout, this.retryCount);
this.retryTimer = setTimeout(() => {
/* If connection is not connected, just leave in suspended, a reattach
* will be triggered once it connects again */
if (this.state === 'suspended' && this.connectionManager.state.sendEvents) {
this.retryTimer = null;
Logger.logAction(
this.logger,
Logger.LOG_MINOR,
'RealtimeChannel retry timer expired',
'attempting a new attach',
);
this.requestState('attaching');
}
}, retryDelay);
}
cancelRetryTimer(): void {
if (this.retryTimer) {
clearTimeout(this.retryTimer as NodeJS.Timeout);
this.retryTimer = null;
}
}
history = async function (
this: RealtimeChannel,
params: RealtimeHistoryParams | null,
): Promise<PaginatedResult<Message>> {
Logger.logAction(this.logger, Logger.LOG_MICRO, 'RealtimeChannel.history()', 'channel = ' + this.name);
// We fetch this first so that any plugin-not-provided error takes priority over other errors
const restMixin = this.client.rest.channelMixin;
if (params && params.untilAttach) {
if (this.state !== 'attached') {
throw new ErrorInfo('option untilAttach requires the channel to be attached', 40000, 400);
}
if (!this.properties.attachSerial) {
throw new ErrorInfo(
'untilAttach was specified and channel is attached, but attachSerial is not defined',
40000,