Skip to content

Commit

Permalink
Merge pull request #1459 from ably/react-hooks-agent-channel-param
Browse files Browse the repository at this point in the history
refactor: send react-hooks agent as channel param
  • Loading branch information
owenpearson authored Oct 19, 2023
2 parents 0d7dd24 + f38c5a7 commit a35b65c
Show file tree
Hide file tree
Showing 8 changed files with 67 additions and 26 deletions.
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
2. Create a new branch for the release, for example `release/1.2.3`
3. Update the CHANGELOG.md with any customer-affecting changes since the last release and add this to the git index
4. Run `npm version <VERSION_NUMBER> --no-git-tag-version` with the new version and add the changes to the git index
5. Update the version number to the new version in `src/platform/react-hooks/src/AblyProvider.tsx`
5. Update the version number to the new version in `src/platform/react-hooks/src/AblyReactHooks.ts`
6. Create a PR for the release branch
7. Once the release PR is landed to the `main` branch, checkout the `main` branch locally (remember to pull the remote changes) and run `npm run build`
8. Run `git tag <VERSION_NUMBER>` with the new version and push the tag to git
Expand Down
15 changes: 14 additions & 1 deletion src/common/lib/client/realtimechannel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,20 @@ class RealtimeChannel extends Channel {
}

_shouldReattachToSetOptions(options?: API.Types.ChannelOptions) {
return (this.state === 'attached' || this.state === 'attaching') && (options?.params || options?.modes);
if (!(this.state === 'attached' || this.state === 'attaching')) {
return false;
}
if (options?.params) {
if (!this.params || !Utils.shallowEquals(this.params, options.params)) {
return true;
}
}
if (options?.modes) {
if (!this.modes || !Utils.arrEquals(options.modes, this.modes)) {
return true;
}
}
return false;
}

publish(...args: any[]): void | Promise<void> {
Expand Down
13 changes: 11 additions & 2 deletions src/common/lib/util/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -318,10 +318,10 @@ export const arrFilter = (Array.prototype.filter as unknown)
};

export const arrEvery = (Array.prototype.every as unknown)
? function <T>(arr: Array<T>, fn: (value: T, index?: number, arr?: Array<T>) => boolean) {
? function <T>(arr: Array<T>, fn: (value: T, index: number, arr: Array<T>) => boolean) {
return arr.every(fn);
}
: function <T>(arr: Array<T>, fn: (value: T, index?: number, arr?: Array<T>) => boolean) {
: function <T>(arr: Array<T>, fn: (value: T, index: number, arr: Array<T>) => boolean) {
const len = arr.length;
for (let i = 0; i < len; i++) {
if (!fn(arr[i], i, arr)) {
Expand Down Expand Up @@ -604,3 +604,12 @@ export function toBase64(str: string) {
}
return stringifyBase64(parseUtf8(str));
}

export function arrEquals(a: any[], b: any[]) {
return (
a.length === b.length &&
arrEvery(a, function (val, i) {
return val === b[i];
})
);
}
13 changes: 0 additions & 13 deletions src/platform/react-hooks/src/AblyProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ import * as Ably from 'ably';
import { Types } from '../../../../ably.js';
import React, { useMemo } from 'react';

const version = '1.2.45';

const canUseSymbol = typeof Symbol === 'function' && typeof Symbol.for === 'function';

interface AblyProviderProps {
Expand All @@ -28,8 +26,6 @@ export function getContext(ctxId = 'default'): AblyContextType {
return ctxMap[ctxId];
}

let hasSentAgent = false;

export const AblyProvider = ({ client, children, id = 'default' }: AblyProviderProps) => {
if (!client) {
throw new Error('AblyProvider: the `client` prop is required');
Expand All @@ -46,14 +42,5 @@ export const AblyProvider = ({ client, children, id = 'default' }: AblyProviderP
context = ctxMap[id] = React.createContext(realtime ?? 1);
}

React.useEffect(() => {
if (!hasSentAgent) {
hasSentAgent = true;
realtime.request('GET', '/time', null, null, {
'Ably-Agent': `react-hooks-time-ping/${version}`,
});
}
});

return <context.Provider value={realtime}>{children}</context.Provider>;
};
12 changes: 12 additions & 0 deletions src/platform/react-hooks/src/AblyReactHooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,15 @@ export type ChannelNameAndId = {
id?: string;
};
export type ChannelParameters = string | ChannelNameAndOptions;

export const version = '1.2.45';

export function channelOptionsWithAgent(options?: Types.ChannelOptions) {
return {
...options,
params: {
...options?.params,
agent: `react-hooks/${version}`,
},
};
}
9 changes: 6 additions & 3 deletions src/platform/react-hooks/src/hooks/useChannel.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Types } from '../../../../../ably.js';
import { useEffect, useMemo, useRef } from 'react';
import { ChannelParameters } from '../AblyReactHooks.js';
import { channelOptionsWithAgent, ChannelParameters } from '../AblyReactHooks.js';
import { useAbly } from './useAbly.js';
import { useStateErrors } from './useStateErrors.js';

Expand Down Expand Up @@ -45,13 +45,16 @@ export function useChannel(
const channelOptionsRef = useRef(channelOptions);
const ablyMessageCallbackRef = useRef(ablyMessageCallback);

const channel = useMemo(() => ably.channels.get(channelName, channelOptionsRef.current), [ably, channelName]);
const channel = useMemo(
() => ably.channels.get(channelName, channelOptionsWithAgent(channelOptionsRef.current)),
[ably, channelName]
);

const { connectionError, channelError } = useStateErrors(channelHookOptions);

useEffect(() => {
if (channelOptionsRef.current !== channelOptions && channelOptions) {
channel.setOptions(channelOptions);
channel.setOptions(channelOptionsWithAgent(channelOptions));
}
channelOptionsRef.current = channelOptions;
}, [channel, channelOptions]);
Expand Down
19 changes: 16 additions & 3 deletions src/platform/react-hooks/src/hooks/usePresence.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Types } from '../../../../../ably.js';
import { useCallback, useEffect, useState } from 'react';
import { ChannelParameters } from '../AblyReactHooks.js';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { channelOptionsWithAgent, ChannelParameters } from '../AblyReactHooks.js';
import { useAbly } from './useAbly.js';
import { useStateErrors } from './useStateErrors.js';

Expand Down Expand Up @@ -28,11 +28,24 @@ export function usePresence<T = any>(

const subscribeOnly = typeof channelNameOrNameAndOptions === 'string' ? false : params.subscribeOnly;

const channel = ably.channels.get(params.channelName, params.options);
const channelOptions = params.options;
const channelOptionsRef = useRef(channelOptions);

const channel = useMemo(
() => ably.channels.get(params.channelName, channelOptionsWithAgent(channelOptionsRef.current)),
[ably, params.channelName]
);
const skip = params.skip;

const { connectionError, channelError } = useStateErrors(params);

useEffect(() => {
if (channelOptionsRef.current !== channelOptions && channelOptions) {
channel.setOptions(channelOptionsWithAgent(channelOptions));
}
channelOptionsRef.current = channelOptions;
}, [channel, channelOptions]);

const [presenceData, updatePresenceData] = useState<Array<PresenceMessage<T>>>([]);

const updatePresence = async (message?: Types.PresenceMessage) => {
Expand Down
10 changes: 7 additions & 3 deletions test/realtime/channel.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -647,7 +647,9 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async

try {
realtime.channels.get(testName, {
params: params,
params: {
modes: 'subscribe',
},
});
} catch (err) {
try {
Expand Down Expand Up @@ -714,7 +716,9 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async
var setOptionsReturned = false;
channel.setOptions(
{
params: params,
params: {
modes: 'publish',
},
},
function () {
/* Wait a tick so we don' depend on whether the update event runs the
Expand Down Expand Up @@ -743,7 +747,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async
var setOptionsReturned = false;
channel.setOptions(
{
modes: modes,
modes: ['subscribe'],
},
function () {
Ably.Realtime.Platform.Config.nextTick(function () {
Expand Down

0 comments on commit a35b65c

Please sign in to comment.