Skip to content

Commit

Permalink
feat: RealtimeChannel.attach returns ChannelStateChange
Browse files Browse the repository at this point in the history
Makes it so that `RealtimeChannel.attach` exposes the
`ChannelStateChange` via whatever async api (invoke callback or fulfill promise).
This makes it easy for users to access flags on the `ChannelStateChange`
to access information about the attachment.
  • Loading branch information
owenpearson committed Jun 29, 2023
1 parent 3915bcd commit 8a50060
Show file tree
Hide file tree
Showing 3 changed files with 106 additions and 26 deletions.
52 changes: 32 additions & 20 deletions ably.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2556,9 +2556,9 @@ declare namespace Types {
/**
* Attach to this channel ensuring the channel is created in the Ably system and all messages published on the channel are received by any channel listeners registered using {@link RealtimeChannelCallbacks.subscribe | `subscribe()`}. Any resulting channel state change will be emitted to any listeners registered using the {@link EventEmitter.on | `on()`} or {@link EventEmitter.once | `once()`} methods. As a convenience, `attach()` is called implicitly if {@link RealtimeChannelCallbacks.subscribe | `subscribe()`} for the channel is called, or {@link RealtimePresenceCallbacks.enter | `enter()`} or {@link RealtimePresenceCallbacks.subscribe | `subscribe()`} are called on the {@link RealtimePresenceCallbacks} object for this channel.
*
* @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
* @param callback - A function which will be called upon completion of the operation. If the operation succeeded and the channel became attached, then the function will be called with a {@link ChannelStateChange} object. If the channel was already attached the function will be called with `null`. If it failed, the function will be called with information about the error.
*/
attach(callback?: errorCallback): void;
attach(callback?: StandardCallback<ChannelStateChange | null>): void;
/**
* Detach from this channel. Any resulting channel state change is emitted to any listeners registered using the {@link EventEmitter.on | `on()`} or {@link EventEmitter.once | `once()`} methods. Once all clients globally have detached from the channel, the channel will be released in the Ably service within two minutes.
*
Expand Down Expand Up @@ -2590,32 +2590,44 @@ declare namespace Types {
*
* @param event - The event name.
* @param listener - An event listener function.
* @param callbackWhenAttached - A function which will be called upon completion of the channel {@link RealtimeChannelCallbacks.attach | `attach()`} operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
* @param callbackWhenAttached - A function which will be called upon completion of the channel {@link RealtimeChannelCallbacks.attach | `attach()`} operation. If the operation succeeded and the channel became attached, then the function will be called with a {@link ChannelStateChange} object. If the channel was already attached the function will be called with `null`. If it failed, the function will be called with information about the error.
*/
subscribe(event: string, listener?: messageCallback<Message>, callbackWhenAttached?: errorCallback): void;
subscribe(
event: string,
listener?: messageCallback<Message>,
callbackWhenAttached?: StandardCallback<ChannelStateChange | null>
): void;
/**
* Registers a listener for messages on this channel for multiple event name values.
*
* @param events - An array of event names.
* @param listener - An event listener function.
* @param callbackWhenAttached - A function which will be called upon completion of the channel {@link RealtimeChannelCallbacks.attach | `attach()`} operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
* @param callbackWhenAttached - A function which will be called upon completion of the channel {@link RealtimeChannelCallbacks.attach | `attach()`} operation. If the operation succeeded and the channel became attached, then the function will be called with a {@link ChannelStateChange} object. If the channel was already attached the function will be called with `null`. If it failed, the function will be called with information about the error.
*/
subscribe(events: Array<string>, listener?: messageCallback<Message>, callbackWhenAttached?: errorCallback): void;
subscribe(
events: Array<string>,
listener?: messageCallback<Message>,
callbackWhenAttached?: StandardCallback<ChannelStateChange | null>
): void;
/**
* Registers a listener for messages on this channel that match the supplied filter.
*
* @param filter - A {@link MessageFilter}.
* @param listener - An event listener function.
* @param callbackWhenAttached - A function which will be called upon completion of the channel {@link RealtimeChannelCallbacks.attach | `attach()`} operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
* @param callbackWhenAttached - A function which will be called upon completion of the channel {@link RealtimeChannelCallbacks.attach | `attach()`} operation. If the operation succeeded and the channel became attached, then the function will be called with a {@link ChannelStateChange} object. If the channel was already attached the function will be called with `null`. If it failed, the function will be called with information about the error.
*/
subscribe(filter: MessageFilter, listener?: messageCallback<Message>, callbackWhenAttached?: errorCallback): void;
subscribe(
filter: MessageFilter,
listener?: messageCallback<Message>,
callbackWhenAttached?: StandardCallback<ChannelStateChange | null>
): void;
/**
* Registers a listener for messages on this channel. The caller supplies a listener function, which is called each time one or more messages arrives on the channel.
*
* @param listener - An event listener function.
* @param callbackWhenAttached - A function which will be called upon completion of the channel {@link RealtimeChannelCallbacks.attach | `attach()`} operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
* @param callbackWhenAttached - A function which will be called upon completion of the channel {@link RealtimeChannelCallbacks.attach | `attach()`} operation. If the operation succeeded and the channel became attached, then the function will be called with a {@link ChannelStateChange} object. If the channel was already attached the function will be called with `null`. If it failed, the function will be called with information about the error.
*/
subscribe(listener: messageCallback<Message>, callbackWhenAttached?: errorCallback): void;
subscribe(listener: messageCallback<Message>, callbackWhenAttached?: StandardCallback<ChannelStateChange>): void;
/**
* Publishes a single message to the channel with the given event name and payload. When publish is called with this client library, it won't attempt to implicitly attach to the channel, so long as [transient publishing](https://ably.com/docs/realtime/channels#transient-publish) is available in the library. Otherwise, the client will implicitly attach.
*
Expand Down Expand Up @@ -2666,9 +2678,9 @@ declare namespace Types {
/**
* Attach to this channel ensuring the channel is created in the Ably system and all messages published on the channel are received by any channel listeners registered using {@link RealtimeChannelPromise.subscribe | `subscribe()`}. Any resulting channel state change will be emitted to any listeners registered using the {@link EventEmitter.on | `on()`} or {@link EventEmitter.once | `once()`} methods. As a convenience, `attach()` is called implicitly if {@link RealtimeChannelPromise.subscribe | `subscribe()`} for the channel is called, or {@link RealtimePresencePromise.enter | `enter()`} or {@link RealtimePresencePromise.subscribe | `subscribe()`} are called on the {@link RealtimePresencePromise} object for this channel.
*
* @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
* @returns A promise which, upon success, if the channel became attached will be fulfilled with a {@link ChannelStateChange} object. If the channel was already attached the promise will be fulfilled with `null`. Upon failure, the promise will be rejected with an {@link ErrorInfo} object.
*/
attach(): Promise<void>;
attach(): Promise<ChannelStateChange | null>;
/**
* Detach from this channel. Any resulting channel state change is emitted to any listeners registered using the {@link EventEmitter.on | `on()`} or {@link EventEmitter.once | `once()`} methods. Once all clients globally have detached from the channel, the channel will be released in the Ably service within two minutes.
*
Expand All @@ -2694,32 +2706,32 @@ declare namespace Types {
*
* @param event - The event name.
* @param listener - An event listener function.
* @returns A promise which resolves upon success of the channel {@link RealtimeChannelPromise.attach | `attach()`} operation and rejects with an {@link ErrorInfo} object upon its failure.
* @returns A promise which, upon successful attachment to the channel, will be fulfilled with a {@link ChannelStateChange} object. If the channel was already attached the promise will be resolved with `null`. Upon failure, the promise will be rejected with an {@link ErrorInfo} object.
*/
subscribe(event: string, listener?: messageCallback<Message>): Promise<void>;
subscribe(event: string, listener?: messageCallback<Message>): Promise<ChannelStateChange | null>;
/**
* Registers a listener for messages on this channel for multiple event name values.
*
* @param events - An array of event names.
* @param listener - An event listener function.
* @returns A promise which resolves upon success of the channel {@link RealtimeChannelPromise.attach | `attach()`} operation and rejects with an {@link ErrorInfo} object upon its failure.
* @returns A promise which, upon successful attachment to the channel, will be fulfilled with a {@link ChannelStateChange} object. If the channel was already attached the promise will be resolved with `null`. Upon failure, the promise will be rejected with an {@link ErrorInfo} object.
*/
subscribe(events: Array<string>, listener?: messageCallback<Message>): Promise<void>;
subscribe(events: Array<string>, listener?: messageCallback<Message>): Promise<ChannelStateChange | null>;
/**
* Registers a listener for messages on this channel that match the supplied filter.
*
* @param filter - A {@link MessageFilter}.
* @param listener - An event listener function.
* @returns A promise which resolves upon success of the channel {@link RealtimeChannelPromise.attach | `attach()`} operation and rejects with an {@link ErrorInfo} object upon its failure.
* @returns A promise which, upon successful attachment to the channel, will be fulfilled with a {@link ChannelStateChange} object. If the channel was already attached the promise will be resolved with `null`. Upon failure, the promise will be rejected with an {@link ErrorInfo} object.
*/
subscribe(filter: MessageFilter, listener?: messageCallback<Message>): Promise<void>;
subscribe(filter: MessageFilter, listener?: messageCallback<Message>): Promise<ChannelStateChange | null>;
/**
* Registers a listener for messages on this channel. The caller supplies a listener function, which is called each time one or more messages arrives on the channel.
*
* @param callback - An event listener function.
* @returns A promise which resolves upon success of the channel {@link RealtimeChannelPromise.attach | `attach()`} operation and rejects with an {@link ErrorInfo} object upon its failure.
* @returns A promise which, upon successful attachment to the channel, will be fulfilled with a {@link ChannelStateChange} object. If the channel was already attached the promise will be resolved with `null`. Upon failure, the promise will be rejected with an {@link ErrorInfo} object.
*/
subscribe(callback: messageCallback<Message>): Promise<void>;
subscribe(callback: messageCallback<Message>): Promise<ChannelStateChange | null>;
/**
* Publishes a single message to the channel with the given event name and payload. When publish is called with this client library, it won't attempt to implicitly attach to the channel, so long as [transient publishing](https://ably.com/docs/realtime/channels#transient-publish) is available in the library. Otherwise, the client will implicitly attach.
*
Expand Down
19 changes: 13 additions & 6 deletions src/common/lib/client/realtimechannel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import ConnectionErrors from '../transport/connectionerrors';
import * as API from '../../../../ably';
import ConnectionManager from '../transport/connectionmanager';
import ConnectionStateChange from './connectionstatechange';
import { ErrCallback, PaginatedResultCallback } from '../../types/utils';
import { ErrCallback, PaginatedResultCallback, StandardCallback } from '../../types/utils';
import Realtime from './realtime';

interface RealtimeHistoryParams {
Expand Down Expand Up @@ -272,7 +272,10 @@ class RealtimeChannel extends Channel {
}
}

attach(flags?: API.Types.ChannelMode[] | ErrCallback, callback?: ErrCallback): void | Promise<void> {
attach(
flags?: API.Types.ChannelMode[] | ErrCallback,
callback?: StandardCallback<ChannelStateChange | null>
): void | Promise<ChannelStateChange> {
let _flags: API.Types.ChannelMode[] | null | undefined;
if (typeof flags === 'function') {
callback = flags;
Expand All @@ -296,14 +299,18 @@ class RealtimeChannel extends Channel {
* current mode differs from requested mode */
this._requestedFlags = _flags as API.Types.ChannelMode[];
} else if (this.state === 'attached') {
callback();
callback(null, null);
return;
}

this._attach(false, null, callback);
}

_attach(forceReattach: boolean, attachReason: ErrorInfo | null, callback?: ErrCallback): void {
_attach(
forceReattach: boolean,
attachReason: ErrorInfo | null,
callback?: StandardCallback<ChannelStateChange>
): void {
if (!callback) {
callback = function (err?: ErrorInfo | null) {
if (err) {
Expand All @@ -325,7 +332,7 @@ class RealtimeChannel extends Channel {
this.once(function (this: { event: string }, stateChange: ChannelStateChange) {
switch (this.event) {
case 'attached':
callback?.();
callback?.(null, stateChange);
break;
case 'detached':
case 'suspended':
Expand Down Expand Up @@ -422,7 +429,7 @@ class RealtimeChannel extends Channel {
this.sendMessage(msg, callback || noop);
}

subscribe(...args: unknown[] /* [event], listener, [callback] */): void | Promise<void> {
subscribe(...args: unknown[] /* [event], listener, [callback] */): void | Promise<ChannelStateChange> {
const [event, listener, callback] = RealtimeChannel.processListenerArgs(args);

if (!callback && this.realtime.options.promises) {
Expand Down
61 changes: 61 additions & 0 deletions test/realtime/channel.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1569,5 +1569,66 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async

channel.subscribe(subscriber);
});

it('attach_returns_state_change', function (done) {
var realtime = helper.AblyRealtime();
var channelName = 'attach_returns_state_chnage';
var channel = realtime.channels.get(channelName);
channel.attach(function (err, stateChange) {
if (err) {
closeAndFinish(done, realtime, err);
return;
}

try {
expect(stateChange.current).to.equal('attached');
expect(stateChange.previous).to.equal('attaching');
} catch (err) {
closeAndFinish(done, realtime, err);
return;
}

// for an already-attached channel, null is returned
channel.attach(function (err, stateChange) {
if (err) {
closeAndFinish(done, realtime, err);
return;
}

try {
expect(stateChange).to.equal(null);
} catch (err) {
closeAndFinish(done, realtime, err);
return;
}
closeAndFinish(done, realtime);
});
});
});

it('subscribe_returns_state_change', function (done) {
var realtime = helper.AblyRealtime();
var channelName = 'subscribe_returns_state_chnage';
var channel = realtime.channels.get(channelName);
channel.subscribe(
function () {}, // message listener
// attach callback
function (err, stateChange) {
if (err) {
closeAndFinish(done, realtime, err);
return;
}

try {
expect(stateChange.current).to.equal('attached');
expect(stateChange.previous).to.equal('attaching');
} catch (err) {
closeAndFinish(done, realtime, err);
return;
}
closeAndFinish(done, realtime);
}
);
});
});
});

0 comments on commit 8a50060

Please sign in to comment.