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 27, 2023
1 parent 87b76d5 commit 875282c
Show file tree
Hide file tree
Showing 25 changed files with 454 additions and 389 deletions.
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
17 changes: 10 additions & 7 deletions src/common/lib/transport/connectionmanager.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import ProtocolMessage from 'common/lib/types/protocolmessage';
import ProtocolMessage, {
actions,
stringify as stringifyProtocolMessage,
fromValues as protocolMessageFromValues,
} from 'common/lib/types/protocolmessage';
import * as Utils from 'common/lib/util/utils';
import Protocol, { PendingMessage } from './protocol';
import Defaults, { getAgentString } from 'common/lib/util/defaults';
Expand All @@ -10,7 +14,7 @@ import ConnectionStateChange from 'common/lib/client/connectionstatechange';
import ConnectionErrors, { isRetriable } from './connectionerrors';
import ErrorInfo, { IPartialErrorInfo, PartialErrorInfo } from 'common/lib/types/errorinfo';
import Auth from 'common/lib/client/auth';
import Message from 'common/lib/types/message';
import Message, { getMessagesSize } from 'common/lib/types/message';
import Multicaster, { MulticasterInstance } from 'common/lib/util/multicaster';
import Transport, { TransportCtor } from './transport';
import * as API from '../../../../ably';
Expand All @@ -24,7 +28,6 @@ let globalObject = typeof global !== 'undefined' ? global : typeof window !== 'u

const haveWebStorage = () => typeof Platform.WebStorage !== 'undefined' && Platform.WebStorage?.localSupported;
const haveSessionStorage = () => typeof Platform.WebStorage !== 'undefined' && Platform.WebStorage?.sessionSupported;
const actions = ProtocolMessage.Action;
const noop = function () {};
const transportPreferenceName = 'ably-transport-preference';

Expand Down Expand Up @@ -62,7 +65,7 @@ function bundleWith(dest: ProtocolMessage, src: ProtocolMessage, maxSize: number
}
const kind = action === actions.PRESENCE ? 'presence' : 'messages',
proposed = (dest as Record<string, any>)[kind].concat((src as Record<string, any>)[kind]),
size = Message.getMessagesSize(proposed);
size = getMessagesSize(proposed);
if (size > maxSize) {
/* RTL6d1 */
return false;
Expand Down Expand Up @@ -732,7 +735,7 @@ class ConnectionManager extends EventEmitter {
// Send ACTIVATE to tell the server to make this transport the
// active transport, which suspends channels until we re-attach.
transport.send(
ProtocolMessage.fromValues({
protocolMessageFromValues({
action: actions.ACTIVATE,
})
);
Expand Down Expand Up @@ -1777,7 +1780,7 @@ class ConnectionManager extends EventEmitter {
activeTransport.onAuthUpdated(tokenDetails);
}

const authMsg = ProtocolMessage.fromValues({
const authMsg = protocolMessageFromValues({
action: actions.AUTH,
auth: {
accessToken: tokenDetails.token,
Expand Down Expand Up @@ -1911,7 +1914,7 @@ class ConnectionManager extends EventEmitter {
return;
}
if (Logger.shouldLog(Logger.LOG_MICRO)) {
Logger.logAction(Logger.LOG_MICRO, 'ConnectionManager.send()', 'queueing msg; ' + ProtocolMessage.stringify(msg));
Logger.logAction(Logger.LOG_MICRO, 'ConnectionManager.send()', 'queueing msg; ' + stringifyProtocolMessage(msg));
}
this.queue(msg, callback);
}
Expand Down
Loading

0 comments on commit 875282c

Please sign in to comment.