Skip to content

Commit

Permalink
Remove static stuff from *Message classes
Browse files Browse the repository at this point in the history
Replace them by standalone exports, which can be tree-shaken.

(My eye was in particular caught by the Message.encrypt function, which
I was thinking it would be good to — at some point — bundle only if the
Crypto module is used. This change isn’t made here though.)
  • Loading branch information
lawrence-forooghian committed Nov 16, 2023
1 parent 354071a commit 4ae8580
Show file tree
Hide file tree
Showing 17 changed files with 452 additions and 384 deletions.
4 changes: 2 additions & 2 deletions src/common/lib/client/defaultrealtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import ClientOptions from '../../types/ClientOptions';
import { allCommonModules } from './modulesmap';
import * as Utils from '../util/utils';
import ConnectionManager from '../transport/connectionmanager';
import ProtocolMessage from '../types/protocolmessage';
import { DefaultProtocolMessage } from '../types/defaultprotocolmessage';
import Platform from 'common/platform';
import { DefaultMessage } from '../types/defaultmessage';
import { MsgPack } from 'common/types/msgpack';
Expand Down Expand Up @@ -34,7 +34,7 @@ export class DefaultRealtime extends BaseRealtime {

static Utils = Utils;
static ConnectionManager = ConnectionManager;
static ProtocolMessage = ProtocolMessage;
static ProtocolMessage = DefaultProtocolMessage;

private static _Crypto: typeof Platform.Crypto = null;
static get Crypto() {
Expand Down
48 changes: 31 additions & 17 deletions src/common/lib/client/realtimechannel.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,27 @@
import ProtocolMessage from '../types/protocolmessage';
import ProtocolMessage, {
actions,
channelModes,
fromValues as protocolMessageFromValues,
} from '../types/protocolmessage';
import EventEmitter from '../util/eventemitter';
import * as Utils from '../util/utils';
import Logger from '../util/logger';
import RealtimePresence from './realtimepresence';
import Message, { CipherOptions } from '../types/message';
import Message, {
fromValues as messageFromValues,
fromValuesArray as messagesFromValuesArray,
encodeArray as encodeMessagesArray,
decode as decodeMessage,
getMessagesSize,
CipherOptions,
} from '../types/message';
import ChannelStateChange from './channelstatechange';
import ErrorInfo, { IPartialErrorInfo, PartialErrorInfo } from '../types/errorinfo';
import PresenceMessage, { fromValues as presenceMessageFromValues } from '../types/presencemessage';
import PresenceMessage, {
fromValues as presenceMessageFromValues,
fromValuesArray as presenceMessagesFromValuesArray,
decode as decodePresenceMessage,
} from '../types/presencemessage';
import ConnectionErrors from '../transport/connectionerrors';
import * as API from '../../../../ably';
import ConnectionManager from '../transport/connectionmanager';
Expand All @@ -25,7 +40,6 @@ interface RealtimeHistoryParams {
from_serial?: string;
}

const actions = ProtocolMessage.Action;
const noop = function () {};

function validateChannelOptions(options?: API.Types.ChannelOptions) {
Expand All @@ -41,7 +55,7 @@ function validateChannelOptions(options?: API.Types.ChannelOptions) {
if (
!currentMode ||
typeof currentMode !== 'string' ||
!Utils.arrIn(ProtocolMessage.channelModes, String.prototype.toUpperCase.call(currentMode))
!Utils.arrIn(channelModes, String.prototype.toUpperCase.call(currentMode))
) {
return new ErrorInfo('Invalid channel mode: ' + currentMode, 40000, 400);
}
Expand Down Expand Up @@ -230,25 +244,25 @@ class RealtimeChannel extends EventEmitter {
return;
}
if (argCount == 2) {
if (Utils.isObject(messages)) messages = [Message.fromValues(messages)];
else if (Utils.isArray(messages)) messages = Message.fromValuesArray(messages);
if (Utils.isObject(messages)) messages = [messageFromValues(messages)];
else if (Utils.isArray(messages)) messages = messagesFromValuesArray(messages);
else
throw new ErrorInfo(
'The single-argument form of publish() expects a message object or an array of message objects',
40013,
400
);
} else {
messages = [Message.fromValues({ name: args[0], data: args[1] })];
messages = [messageFromValues({ name: args[0], data: args[1] })];
}
const maxMessageSize = this.client.options.maxMessageSize;
Message.encodeArray(messages, this.channelOptions as CipherOptions, (err: Error | null) => {
encodeMessagesArray(messages, this.channelOptions as CipherOptions, (err: Error | null) => {
if (err) {
callback(err);
return;
}
/* RSL1i */
const size = Message.getMessagesSize(messages);
const size = getMessagesSize(messages);
if (size > maxMessageSize) {
callback(
new ErrorInfo(
Expand Down Expand Up @@ -354,7 +368,7 @@ class RealtimeChannel extends EventEmitter {

attachImpl(): void {
Logger.logAction(Logger.LOG_MICRO, 'RealtimeChannel.attachImpl()', 'sending ATTACH message');
const attachMsg = ProtocolMessage.fromValues({
const attachMsg = protocolMessageFromValues({
action: actions.ATTACH,
channel: this.name,
params: this.channelOptions.params,
Expand Down Expand Up @@ -424,7 +438,7 @@ class RealtimeChannel extends EventEmitter {

detachImpl(callback?: ErrCallback): void {
Logger.logAction(Logger.LOG_MICRO, 'RealtimeChannel.detach()', 'sending DETACH message');
const msg = ProtocolMessage.fromValues({ action: actions.DETACH, channel: this.name });
const msg = protocolMessageFromValues({ action: actions.DETACH, channel: this.name });
this.sendMessage(msg, callback || noop);
}

Expand Down Expand Up @@ -479,7 +493,7 @@ class RealtimeChannel extends EventEmitter {
}

/* send sync request */
const syncMessage = ProtocolMessage.fromValues({ action: actions.SYNC, channel: this.name });
const syncMessage = protocolMessageFromValues({ action: actions.SYNC, channel: this.name });
if (this.syncChannelSerial) {
syncMessage.channelSerial = this.syncChannelSerial;
}
Expand All @@ -491,11 +505,11 @@ class RealtimeChannel extends EventEmitter {
}

sendPresence(presence: PresenceMessage | PresenceMessage[], callback?: ErrCallback): void {
const msg = ProtocolMessage.fromValues({
const msg = protocolMessageFromValues({
action: actions.PRESENCE,
channel: this.name,
presence: Utils.isArray(presence)
? PresenceMessage.fromValuesArray(presence)
? presenceMessagesFromValuesArray(presence)
: [presenceMessageFromValues(presence)],
});
this.sendMessage(msg, callback);
Expand Down Expand Up @@ -579,7 +593,7 @@ class RealtimeChannel extends EventEmitter {
for (let i = 0; i < presence.length; i++) {
try {
presenceMsg = presence[i];
await PresenceMessage.decode(presenceMsg, options);
await decodePresenceMessage(presenceMsg, options);
if (!presenceMsg.connectionId) presenceMsg.connectionId = connectionId;
if (!presenceMsg.timestamp) presenceMsg.timestamp = timestamp;
if (!presenceMsg.id) presenceMsg.id = id + ':' + i;
Expand Down Expand Up @@ -635,7 +649,7 @@ class RealtimeChannel extends EventEmitter {
for (let i = 0; i < messages.length; i++) {
const msg = messages[i];
try {
await Message.decode(msg, this._decodingContext);
await decodeMessage(msg, this._decodingContext);
} catch (e) {
/* decrypt failed .. the most likely cause is that we have the wrong key */
Logger.logAction(Logger.LOG_ERROR, 'RealtimeChannel.processMessage()', (e as Error).toString());
Expand Down
12 changes: 8 additions & 4 deletions src/common/lib/client/realtimepresence.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import * as Utils from '../util/utils';
import EventEmitter from '../util/eventemitter';
import Logger from '../util/logger';
import PresenceMessage, { fromValues as presenceMessageFromValues } from '../types/presencemessage';
import PresenceMessage, {
fromValues as presenceMessageFromValues,
fromData as presenceMessageFromData,
encode as encodePresenceMessage,
} from '../types/presencemessage';
import ErrorInfo, { IPartialErrorInfo, PartialErrorInfo } from '../types/errorinfo';
import RealtimeChannel from './realtimechannel';
import Multicaster from '../util/multicaster';
Expand Down Expand Up @@ -147,7 +151,7 @@ class RealtimePresence extends EventEmitter {
'channel = ' + channel.name + ', id = ' + id + ', client = ' + (clientId || '(implicit) ' + getClientId(this))
);

const presence = PresenceMessage.fromData(data);
const presence = presenceMessageFromData(data);
presence.action = action;
if (id) {
presence.id = id;
Expand All @@ -156,7 +160,7 @@ class RealtimePresence extends EventEmitter {
presence.clientId = clientId;
}

PresenceMessage.encode(presence, channel.channelOptions as CipherOptions, (err: IPartialErrorInfo) => {
encodePresenceMessage(presence, channel.channelOptions as CipherOptions, (err: IPartialErrorInfo) => {
if (err) {
callback(err);
return;
Expand Down Expand Up @@ -214,7 +218,7 @@ class RealtimePresence extends EventEmitter {
'RealtimePresence.leaveClient()',
'leaving; channel = ' + this.channel.name + ', client = ' + clientId
);
const presence = PresenceMessage.fromData(data);
const presence = presenceMessageFromData(data);
presence.action = 'leave';
if (clientId) {
presence.clientId = clientId;
Expand Down
21 changes: 14 additions & 7 deletions src/common/lib/client/restchannel.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import * as Utils from '../util/utils';
import Logger from '../util/logger';
import RestPresence from './restpresence';
import Message, { CipherOptions } from '../types/message';
import Message, {
fromValues as messageFromValues,
fromValuesArray as messagesFromValuesArray,
encodeArray as encodeMessagesArray,
serialize as serializeMessage,
getMessagesSize,
CipherOptions,
} from '../types/message';
import ErrorInfo from '../types/errorinfo';
import { PaginatedResult } from './paginatedresource';
import Resource, { ResourceCallback } from './resource';
Expand Down Expand Up @@ -70,13 +77,13 @@ class RestChannel {

if (typeof first === 'string' || first === null) {
/* (name, data, ...) */
messages = [Message.fromValues({ name: first, data: second })];
messages = [messageFromValues({ name: first, data: second })];
params = arguments[2];
} else if (Utils.isObject(first)) {
messages = [Message.fromValues(first)];
messages = [messageFromValues(first)];
params = arguments[1];
} else if (Utils.isArray(first)) {
messages = Message.fromValuesArray(first);
messages = messagesFromValuesArray(first);
params = arguments[1];
} else {
throw new ErrorInfo(
Expand Down Expand Up @@ -106,14 +113,14 @@ class RestChannel {
});
}

Message.encodeArray(messages, this.channelOptions as CipherOptions, (err: Error) => {
encodeMessagesArray(messages, this.channelOptions as CipherOptions, (err: Error) => {
if (err) {
callback(err);
return;
}

/* RSL1i */
const size = Message.getMessagesSize(messages),
const size = getMessagesSize(messages),
maxMessageSize = options.maxMessageSize;
if (size > maxMessageSize) {
callback(
Expand All @@ -130,7 +137,7 @@ class RestChannel {
return;
}

this._publish(Message.serialize(messages, client._MsgPack, format), headers, params, callback);
this._publish(serializeMessage(messages, client._MsgPack, format), headers, params, callback);
});
}

Expand Down
4 changes: 2 additions & 2 deletions src/common/lib/client/restchannelmixin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import RestChannel from './restchannel';
import RealtimeChannel from './realtimechannel';
import * as Utils from '../util/utils';
import { PaginatedResultCallback, StandardCallback } from '../../types/utils';
import Message from '../types/message';
import Message, { fromResponseBody as messageFromResponseBody } from '../types/message';
import Defaults from '../util/defaults';
import PaginatedResource from './paginatedresource';
import Resource from './resource';
Expand Down Expand Up @@ -40,7 +40,7 @@ export class RestChannelMixin {
headers,
unpacked
) {
return await Message.fromResponseBody(body as Message[], options, client._MsgPack, unpacked ? undefined : format);
return await messageFromResponseBody(body as Message[], options, client._MsgPack, unpacked ? undefined : format);
}).get(params as Record<string, unknown>, callback);
}

Expand Down
4 changes: 2 additions & 2 deletions src/common/lib/client/restpresence.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as Utils from '../util/utils';
import Logger from '../util/logger';
import PaginatedResource, { PaginatedResult } from './paginatedresource';
import PresenceMessage from '../types/presencemessage';
import PresenceMessage, { fromResponseBody as presenceMessageFromResponseBody } from '../types/presencemessage';
import { CipherOptions } from '../types/message';
import { PaginatedResultCallback } from '../../types/utils';
import RestChannel from './restchannel';
Expand Down Expand Up @@ -39,7 +39,7 @@ class RestPresence {
headers,
envelope,
async function (body, headers, unpacked) {
return await PresenceMessage.fromResponseBody(
return await presenceMessageFromResponseBody(
body as Record<string, unknown>[],
options as CipherOptions,
client._MsgPack,
Expand Down
4 changes: 2 additions & 2 deletions src/common/lib/client/restpresencemixin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import * as Utils from '../util/utils';
import { PaginatedResultCallback } from '../../types/utils';
import Defaults from '../util/defaults';
import PaginatedResource, { PaginatedResult } from './paginatedresource';
import PresenceMessage from '../types/presencemessage';
import PresenceMessage, { fromResponseBody as presenceMessageFromResponseBody } from '../types/presencemessage';
import { CipherOptions } from '../types/message';
import { RestChannelMixin } from './restchannelmixin';

Expand Down Expand Up @@ -41,7 +41,7 @@ export class RestPresenceMixin {
headers,
unpacked
) {
return await PresenceMessage.fromResponseBody(
return await presenceMessageFromResponseBody(
body as Record<string, unknown>[],
options as CipherOptions,
client._MsgPack,
Expand Down
12 changes: 8 additions & 4 deletions src/common/lib/transport/comettransport.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import * as Utils from '../util/utils';
import ProtocolMessage from '../types/protocolmessage';
import ProtocolMessage, {
actions,
fromValues as protocolMessageFromValues,
fromDeserialized as protocolMessageFromDeserialized,
} from '../types/protocolmessage';
import Transport from './transport';
import Logger from '../util/logger';
import Defaults from '../util/defaults';
Expand Down Expand Up @@ -29,9 +33,9 @@ function protocolMessageFromRawError(err: ErrorInfo) {
/* err will be either a legacy (non-protocolmessage) comet error response
* (which will have an err.code), or a xhr/network error (which won't). */
if (shouldBeErrorAction(err)) {
return [ProtocolMessage.fromValues({ action: ProtocolMessage.Action.ERROR, error: err })];
return [protocolMessageFromValues({ action: actions.ERROR, error: err })];
} else {
return [ProtocolMessage.fromValues({ action: ProtocolMessage.Action.DISCONNECTED, error: err })];
return [protocolMessageFromValues({ action: actions.DISCONNECTED, error: err })];
}
}

Expand Down Expand Up @@ -344,7 +348,7 @@ abstract class CometTransport extends Transport {
try {
const items = this.decodeResponse(responseData);
if (items && items.length)
for (let i = 0; i < items.length; i++) this.onProtocolMessage(ProtocolMessage.fromDeserialized(items[i]));
for (let i = 0; i < items.length; i++) this.onProtocolMessage(protocolMessageFromDeserialized(items[i]));
} catch (e) {
Logger.logAction(
Logger.LOG_ERROR,
Expand Down
Loading

0 comments on commit 4ae8580

Please sign in to comment.