Skip to content

Commit

Permalink
Add a _MsgPack property to BaseClient
Browse files Browse the repository at this point in the history
The _MsgPack assignment becomes the only place that
Platform.Config.msgpack gets accessed. All other uses now instead access
_MsgPack.

Preparation for #1375 (making MessagePack functionality tree-shakable).
  • Loading branch information
lawrence-forooghian committed Sep 14, 2023
1 parent 6c305a1 commit 913637a
Show file tree
Hide file tree
Showing 14 changed files with 74 additions and 34 deletions.
1 change: 1 addition & 0 deletions src/common/lib/client/baseclient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ class BaseClient {

private readonly _rest: Rest | null;
readonly _Crypto: IUntypedCryptoStatic | null;
readonly _MsgPack = Platform.Config.msgpack;

constructor(options: ClientOptions | string, modules: ModulesMap) {
if (!options) {
Expand Down
4 changes: 2 additions & 2 deletions src/common/lib/client/channel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ class Channel extends EventEmitter {
headers: Record<string, string>,
unpacked?: boolean
) {
return await Message.fromResponseBody(body, options, unpacked ? undefined : format);
return await Message.fromResponseBody(body, options, client._MsgPack, unpacked ? undefined : format);
}).get(params as Record<string, unknown>, callback);
}

Expand Down Expand Up @@ -177,7 +177,7 @@ class Channel extends EventEmitter {
return;
}

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

Expand Down
14 changes: 12 additions & 2 deletions src/common/lib/client/presence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,12 @@ class Presence extends EventEmitter {
headers: Record<string, string>,
unpacked?: boolean
) {
return await PresenceMessage.fromResponseBody(body, options as CipherOptions, unpacked ? undefined : format);
return await PresenceMessage.fromResponseBody(
body,
options as CipherOptions,
client._MsgPack,
unpacked ? undefined : format
);
}).get(params, callback);
}

Expand Down Expand Up @@ -82,7 +87,12 @@ class Presence extends EventEmitter {
headers: Record<string, string>,
unpacked?: boolean
) {
return await PresenceMessage.fromResponseBody(body, options as CipherOptions, unpacked ? undefined : format);
return await PresenceMessage.fromResponseBody(
body,
options as CipherOptions,
client._MsgPack,
unpacked ? undefined : format
);
}).get(params, callback);
}
}
Expand Down
23 changes: 16 additions & 7 deletions src/common/lib/client/push.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ class Admin {

if (client.options.pushFullWait) Utils.mixin(params, { fullWait: 'true' });

const requestBody = Utils.encodeBody(body, format);
const requestBody = Utils.encodeBody(body, client._MsgPack, format);
Resource.post(client, '/push/publish', requestBody, headers, params, null, (err) => callback(err));
}
}
Expand All @@ -71,7 +71,7 @@ class DeviceRegistrations {

if (client.options.pushFullWait) Utils.mixin(params, { fullWait: 'true' });

const requestBody = Utils.encodeBody(body, format);
const requestBody = Utils.encodeBody(body, client._MsgPack, format);
Resource.put(
client,
'/push/deviceRegistrations/' + encodeURIComponent(device.id),
Expand All @@ -85,6 +85,7 @@ class DeviceRegistrations {
!err
? (DeviceDetails.fromResponseBody(
body as Record<string, unknown>,
client._MsgPack,
unpacked ? undefined : format
) as DeviceDetails)
: undefined
Expand Down Expand Up @@ -128,6 +129,7 @@ class DeviceRegistrations {
!err
? (DeviceDetails.fromResponseBody(
body as Record<string, unknown>,
client._MsgPack,
unpacked ? undefined : format
) as DeviceDetails)
: undefined
Expand All @@ -153,7 +155,7 @@ class DeviceRegistrations {
headers: Record<string, string>,
unpacked?: boolean
) {
return DeviceDetails.fromResponseBody(body, unpacked ? undefined : format);
return DeviceDetails.fromResponseBody(body, client._MsgPack, unpacked ? undefined : format);
}).get(params, callback);
}

Expand Down Expand Up @@ -232,7 +234,7 @@ class ChannelSubscriptions {

if (client.options.pushFullWait) Utils.mixin(params, { fullWait: 'true' });

const requestBody = Utils.encodeBody(body, format);
const requestBody = Utils.encodeBody(body, client._MsgPack, format);
Resource.post(
client,
'/push/channelSubscriptions',
Expand All @@ -243,7 +245,12 @@ class ChannelSubscriptions {
function (err, body, headers, unpacked) {
callback(
err,
!err && PushChannelSubscription.fromResponseBody(body as Record<string, any>, unpacked ? undefined : format)
!err &&
PushChannelSubscription.fromResponseBody(
body as Record<string, any>,
client._MsgPack,
unpacked ? undefined : format
)
);
}
);
Expand All @@ -266,7 +273,7 @@ class ChannelSubscriptions {
headers: Record<string, string>,
unpacked?: boolean
) {
return PushChannelSubscription.fromResponseBody(body, unpacked ? undefined : format);
return PushChannelSubscription.fromResponseBody(body, client._MsgPack, unpacked ? undefined : format);
}).get(params, callback);
}

Expand Down Expand Up @@ -308,7 +315,9 @@ class ChannelSubscriptions {
headers: Record<string, string>,
unpacked?: boolean
) {
const parsedBody = (!unpacked && format ? Utils.decodeBody(body, format) : body) as Array<string>;
const parsedBody = (
!unpacked && format ? Utils.decodeBody(body, client._MsgPack, format) : body
) as Array<string>;

for (let i = 0; i < parsedBody.length; i++) {
parsedBody[i] = String(parsedBody[i]);
Expand Down
13 changes: 9 additions & 4 deletions src/common/lib/client/resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import HttpMethods from '../../constants/HttpMethods';
import ErrorInfo, { IPartialErrorInfo, PartialErrorInfo } from '../types/errorinfo';
import BaseClient from './baseclient';
import { ErrnoException } from '../../types/http';
import { MsgPack } from 'common/types/msgpack';

function withAuthDetails(
client: BaseClient,
Expand All @@ -27,7 +28,11 @@ function withAuthDetails(
}
}

function unenvelope<T>(callback: ResourceCallback<T>, format: Utils.Format | null): ResourceCallback<T> {
function unenvelope<T>(
callback: ResourceCallback<T>,
MsgPack: MsgPack,
format: Utils.Format | null
): ResourceCallback<T> {
return (err, body, outerHeaders, unpacked, outerStatusCode) => {
if (err && !body) {
callback(err);
Expand All @@ -36,7 +41,7 @@ function unenvelope<T>(callback: ResourceCallback<T>, format: Utils.Format | nul

if (!unpacked) {
try {
body = Utils.decodeBody(body, format);
body = Utils.decodeBody(body, MsgPack, format);
} catch (e) {
if (Utils.isErrorInfoOrPartialErrorInfo(e)) {
callback(e);
Expand Down Expand Up @@ -204,7 +209,7 @@ class Resource {
}

if (envelope) {
callback = callback && unenvelope(callback, envelope);
callback = callback && unenvelope(callback, client._MsgPack, envelope);
(params = params || {})['envelope'] = envelope;
}

Expand All @@ -221,7 +226,7 @@ class Resource {
let decodedBody = body;
if (headers['content-type']?.indexOf('msgpack') > 0) {
try {
decodedBody = Platform.Config.msgpack.decode(body as Buffer);
decodedBody = client._MsgPack.decode(body as Buffer);
} catch (decodeErr) {
Logger.logAction(
Logger.LOG_MICRO,
Expand Down
4 changes: 2 additions & 2 deletions src/common/lib/client/rest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,8 @@ export class Rest {
callback: StandardCallback<HttpPaginatedResponse<unknown>>
): Promise<HttpPaginatedResponse<unknown>> | void {
const useBinary = this.client.options.useBinaryProtocol,
encoder = useBinary ? Platform.Config.msgpack.encode : JSON.stringify,
decoder = useBinary ? Platform.Config.msgpack.decode : JSON.parse,
encoder = useBinary ? this.client._MsgPack.encode : JSON.stringify,
decoder = useBinary ? this.client._MsgPack.decode : JSON.parse,
format = useBinary ? Utils.Format.msgpack : Utils.Format.json,
envelope = this.client.http.supportsLinkHeaders ? undefined : format;
params = params || {};
Expand Down
6 changes: 4 additions & 2 deletions src/common/lib/transport/websockettransport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,9 @@ class WebSocketTransport extends Transport {
return;
}
try {
wsConnection.send(ProtocolMessage.serialize(message, this.params.format));
wsConnection.send(
ProtocolMessage.serialize(message, this.connectionManager.realtime._MsgPack, this.params.format)
);
} catch (e) {
const msg = 'Exception from ws connection when trying to send: ' + Utils.inspectError(e);
Logger.logAction(Logger.LOG_ERROR, 'WebSocketTransport.send()', msg);
Expand All @@ -119,7 +121,7 @@ class WebSocketTransport extends Transport {
'data received; length = ' + data.length + '; type = ' + typeof data
);
try {
this.onProtocolMessage(ProtocolMessage.deserialize(data, this.format));
this.onProtocolMessage(ProtocolMessage.deserialize(data, this.connectionManager.realtime._MsgPack, this.format));
} catch (e) {
Logger.logAction(
Logger.LOG_ERROR,
Expand Down
4 changes: 3 additions & 1 deletion src/common/lib/types/devicedetails.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { MsgPack } from 'common/types/msgpack';
import * as Utils from '../util/utils';
import ErrorInfo, { IConvertibleToErrorInfo } from './errorinfo';

Expand Down Expand Up @@ -74,10 +75,11 @@ class DeviceDetails {

static fromResponseBody(
body: Array<Record<string, unknown>> | Record<string, unknown>,
MsgPack: MsgPack,
format?: Utils.Format
): DeviceDetails | DeviceDetails[] {
if (format) {
body = Utils.decodeBody(body, format);
body = Utils.decodeBody(body, MsgPack, format);
}

if (Utils.isArray(body)) {
Expand Down
4 changes: 3 additions & 1 deletion src/common/lib/types/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import * as Utils from '../util/utils';
import { Bufferlike as BrowserBufferlike } from '../../../platform/web/lib/util/bufferutils';
import * as API from '../../../../ably';
import { IUntypedCryptoStatic } from 'common/types/ICryptoStatic';
import { MsgPack } from 'common/types/msgpack';

export type CipherOptions = {
channelCipher: {
Expand Down Expand Up @@ -335,10 +336,11 @@ class Message {
static async fromResponseBody(
body: Array<Message>,
options: ChannelOptions | EncodingDecodingContext,
MsgPack: MsgPack,
format?: Utils.Format
): Promise<Message[]> {
if (format) {
body = Utils.decodeBody(body, format);
body = Utils.decodeBody(body, MsgPack, format);
}

for (let i = 0; i < body.length; i++) {
Expand Down
4 changes: 3 additions & 1 deletion src/common/lib/types/presencemessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import Platform from 'common/platform';
import Message, { CipherOptions } from './message';
import * as Utils from '../util/utils';
import * as API from '../../../../ably';
import { MsgPack } from 'common/types/msgpack';

function toActionValue(actionString: string) {
return PresenceMessage.Actions.indexOf(actionString);
Expand Down Expand Up @@ -105,11 +106,12 @@ class PresenceMessage {
static async fromResponseBody(
body: Record<string, unknown>[],
options: CipherOptions,
MsgPack: MsgPack,
format?: Utils.Format
): Promise<PresenceMessage[]> {
const messages: PresenceMessage[] = [];
if (format) {
body = Utils.decodeBody(body, format);
body = Utils.decodeBody(body, MsgPack, format);
}

for (let i = 0; i < body.length; i++) {
Expand Down
5 changes: 3 additions & 2 deletions src/common/lib/types/protocolmessage.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { MsgPack } from 'common/types/msgpack';
import { Types } from '../../../../ably';
import * as Utils from '../util/utils';
import ErrorInfo from './errorinfo';
Expand Down Expand Up @@ -109,8 +110,8 @@ class ProtocolMessage {

static serialize = Utils.encodeBody;

static deserialize = function (serialized: unknown, format?: Utils.Format): ProtocolMessage {
const deserialized = Utils.decodeBody<Record<string, unknown>>(serialized, format);
static deserialize = function (serialized: unknown, MsgPack: MsgPack, format?: Utils.Format): ProtocolMessage {
const deserialized = Utils.decodeBody<Record<string, unknown>>(serialized, MsgPack, format);
return ProtocolMessage.fromDeserialized(deserialized);
};

Expand Down
4 changes: 3 additions & 1 deletion src/common/lib/types/pushchannelsubscription.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { MsgPack } from 'common/types/msgpack';
import * as Utils from '../util/utils';

type PushChannelSubscriptionObject = {
Expand Down Expand Up @@ -36,10 +37,11 @@ class PushChannelSubscription {

static fromResponseBody(
body: Array<Record<string, unknown>> | Record<string, unknown>,
MsgPack: MsgPack,
format?: Utils.Format
): PushChannelSubscription | PushChannelSubscription[] {
if (format) {
body = Utils.decodeBody(body, format) as Record<string, unknown>;
body = Utils.decodeBody(body, MsgPack, format) as Record<string, unknown>;
}

if (Utils.isArray(body)) {
Expand Down
9 changes: 5 additions & 4 deletions src/common/lib/util/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Platform from 'common/platform';
import ErrorInfo, { PartialErrorInfo } from 'common/lib/types/errorinfo';
import { MsgPack } from 'common/types/msgpack';

function randomPosn(arrOrStr: Array<unknown> | string) {
return Math.floor(Math.random() * arrOrStr.length);
Expand Down Expand Up @@ -450,12 +451,12 @@ export function promisify<T>(ob: Record<string, any>, fnName: string, args: IArg
});
}

export function decodeBody<T>(body: unknown, format?: Format | null): T {
return format == 'msgpack' ? Platform.Config.msgpack.decode(body as Buffer) : JSON.parse(String(body));
export function decodeBody<T>(body: unknown, MsgPack: MsgPack, format?: Format | null): T {
return format == 'msgpack' ? MsgPack.decode(body as Buffer) : JSON.parse(String(body));
}

export function encodeBody(body: unknown, format?: Format): string | Buffer {
return format == 'msgpack' ? (Platform.Config.msgpack.encode(body, true) as Buffer) : JSON.stringify(body);
export function encodeBody(body: unknown, MsgPack: MsgPack, format?: Format): string | Buffer {
return format == 'msgpack' ? (MsgPack.encode(body, true) as Buffer) : JSON.stringify(body);
}

export function allToLowerCase(arr: Array<string>): Array<string> {
Expand Down
13 changes: 8 additions & 5 deletions src/platform/nodejs/lib/util/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import { shallowEquals } from 'common/lib/util/utils';

const globalAgentPool: Array<{ options: RestAgentOptions; agents: Agents }> = [];

const handler = function (uri: string, params: unknown, callback?: RequestCallback) {
const handler = function (uri: string, params: unknown, client: BaseClient | null, callback?: RequestCallback) {
return function (err: ErrnoException | null, response?: Response, body?: unknown) {
if (err) {
callback?.(err);
Expand All @@ -42,7 +42,10 @@ const handler = function (uri: string, params: unknown, callback?: RequestCallba
body = JSON.parse(body as string);
break;
case 'application/x-msgpack':
body = Platform.Config.msgpack.decode(body as Buffer);
if (!client) {
throw new ErrorInfo('Cannot use MessagePack without a client', 400, 40000);
}
body = client._MsgPack.decode(body as Buffer);
}
const error = (body as { error: ErrorInfo }).error
? ErrorInfo.fromValues((body as { error: ErrorInfo }).error)
Expand Down Expand Up @@ -230,14 +233,14 @@ const Http: typeof IHttp = class {

(got[method](doOptions) as CancelableRequest<Response>)
.then((res: Response) => {
handler(uri, params, callback)(null, res, res.body);
handler(uri, params, client, callback)(null, res, res.body);
})
.catch((err: ErrnoException) => {
if (err instanceof got.HTTPError) {
handler(uri, params, callback)(null, err.response, err.response.body);
handler(uri, params, client, callback)(null, err.response, err.response.body);
return;
}
handler(uri, params, callback)(err);
handler(uri, params, client, callback)(err);
});
}

Expand Down

0 comments on commit 913637a

Please sign in to comment.