Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
253 changes: 172 additions & 81 deletions dist/web/pubnub.js

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions dist/web/pubnub.min.js

Large diffs are not rendered by default.

8 changes: 7 additions & 1 deletion lib/core/components/abort_signal.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,14 @@ exports.AbortError = AbortError;
* @internal
*/
class AbortSignal extends subject_1.Subject {
/**
* Notify listeners inside `abort()`.
*
* Managed-effect cancellation has to stop an in-flight request, including a retry that is only
* waiting, before the state machine dispatches the next effect.
*/
constructor() {
super(...arguments);
super(true);
this._aborted = false;
}
get aborted() {
Expand Down
1 change: 1 addition & 0 deletions lib/core/components/configuration.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ const makeConfiguration = (base, setupCryptoModule) => {
var _a, _b, _c, _d;
// Set the default retry policy for subscribing (if new subscribe logic not used).
if (!base.retryConfiguration && base.enableEventEngine) {
// Only `Endpoint.Subscribe` and `Endpoint.PresenceHeartbeat` are retried by default.
base.retryConfiguration = retry_policy_1.RetryPolicy.ExponentialRetryPolicy({
minimumDelay: 2,
maximumDelay: 150,
Expand Down
22 changes: 21 additions & 1 deletion lib/core/components/retry-policy.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,15 @@ const categories_1 = __importDefault(require("../constants/categories"));
* @internal
*/
const NON_RETRIABLE_STATUS_CODES = [404, 409];
/**
* Presence heartbeat request path.
*
* Matched strictly so `here now` for a channel named `heartbeat` or `get presence state` for a `heartbeat` user ID stay
* in {@link Endpoint.Presence}. The channel segment can be empty or `,` when only channel groups are used.
*
* @internal
*/
const HEARTBEAT_PATH = /^\/v2\/presence\/sub-key\/[^/]+\/channel\/[^/]*\/heartbeat$/;
// --------------------------------------------------------
// ------------------------ Types -------------------------
// --------------------------------------------------------
Expand Down Expand Up @@ -51,9 +60,18 @@ var Endpoint;
* - `set presence state`
* - `here now`
* - `where now`
* - `heartbeat`
* - `leave`
*
* **Note:** `heartbeat` isn't part of this group. Use {@link Endpoint.PresenceHeartbeat} to control its retry.
*/
Endpoint["Presence"] = "PresenceEndpoint";
/**
* The endpoint to announce `user_id` presence on channels and channel groups.
*
* This is related to the following functionality:
* - `heartbeat`
*/
Endpoint["PresenceHeartbeat"] = "PresenceHeartbeatEndpoint";
/**
* The endpoint to access and manage files in channel-specific storage.
*
Expand Down Expand Up @@ -248,6 +266,8 @@ const endpointFromRequest = (req) => {
endpoint = Endpoint.Subscribe;
else if (req.path.startsWith('/publish/') || req.path.startsWith('/signal/'))
endpoint = Endpoint.MessageSend;
else if (HEARTBEAT_PATH.test(req.path))
endpoint = Endpoint.PresenceHeartbeat;
else if (req.path.startsWith('/v2/presence'))
endpoint = Endpoint.Presence;
else if (req.path.startsWith('/v2/history') || req.path.startsWith('/v3/history'))
Expand Down
41 changes: 39 additions & 2 deletions lib/core/components/subscription-manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const utils_1 = require("../utils");
const reconnection_manager_1 = require("./reconnection_manager");
const categories_1 = __importDefault(require("../constants/categories"));
const deduping_manager_1 = require("./deduping_manager");
const abort_signal_1 = require("./abort_signal");
/**
* Subscription loop manager.
*
Expand All @@ -37,6 +38,13 @@ class SubscriptionManager {
this.subscribeCall = subscribeCall;
this.heartbeatCall = heartbeatCall;
this.leaveCall = leaveCall;
/**
* Abort signal for the latest heartbeat request.
*
* Aborting it also cancels a heartbeat retry that is still waiting, so a retry can't announce presence after the
* heartbeat loop stopped or channels were removed.
*/
this.heartbeatAbortSignal = null;
/**
* Whether user code in event handlers requested disconnection or not.
*
Expand Down Expand Up @@ -146,12 +154,15 @@ class SubscriptionManager {
let { channels, channelGroups } = parameters;
const actualChannelGroups = new Set();
const actualChannels = new Set();
let heartbeatTargetsChanged = false;
channels === null || channels === void 0 ? void 0 : channels.forEach((channel) => {
if (channel in this.channels) {
delete this.channels[channel];
actualChannels.add(channel);
if (channel in this.heartbeatChannels)
if (channel in this.heartbeatChannels) {
delete this.heartbeatChannels[channel];
heartbeatTargetsChanged = true;
}
}
if (channel in this.presenceState)
delete this.presenceState[channel];
Expand All @@ -164,8 +175,10 @@ class SubscriptionManager {
if (group in this.channelGroups) {
delete this.channelGroups[group];
actualChannelGroups.add(group);
if (group in this.heartbeatChannelGroups)
if (group in this.heartbeatChannelGroups) {
delete this.heartbeatChannelGroups[group];
heartbeatTargetsChanged = true;
}
}
if (group in this.presenceState)
delete this.presenceState[group];
Expand All @@ -174,6 +187,9 @@ class SubscriptionManager {
actualChannelGroups.add(group);
}
});
// A pending heartbeat (or its retry) still targets removed channels. Cancel it before `leave` is sent.
if (heartbeatTargetsChanged)
this.abortHeartbeat();
// There is no need to unsubscribe to empty list of data sources.
if (actualChannels.size === 0 && actualChannelGroups.size === 0)
return;
Expand Down Expand Up @@ -427,11 +443,22 @@ class SubscriptionManager {
* Stop timer which trigger {@link HeartbeatRequest} sending with configured presence intervals.
*/
stopHeartbeatTimer() {
this.abortHeartbeat();
if (!this.heartbeatTimer)
return;
clearInterval(this.heartbeatTimer);
this.heartbeatTimer = null;
}
/**
* Cancel the latest heartbeat request, including a retry that is still waiting.
*/
abortHeartbeat() {
if (!this.heartbeatAbortSignal)
return;
const abortSignal = this.heartbeatAbortSignal;
this.heartbeatAbortSignal = null;
abortSignal.abort();
}
/**
* Send heartbeat request.
*/
Expand All @@ -441,12 +468,22 @@ class SubscriptionManager {
// There is no need to start heartbeat loop if there is no channels and groups to use.
if (heartbeatChannels.length === 0 && heartbeatChannelGroups.length === 0)
return;
// A newer heartbeat replaces a previous one that is still waiting for a retry.
this.abortHeartbeat();
const abortSignal = new abort_signal_1.AbortSignal();
this.heartbeatAbortSignal = abortSignal;
this.heartbeatCall({
abortSignal,
channels: heartbeatChannels,
channelGroups: heartbeatChannelGroups,
heartbeat: this.configuration.getPresenceTimeout(),
state: this.presenceState,
}, (status) => {
if (this.heartbeatAbortSignal === abortSignal)
this.heartbeatAbortSignal = null;
// Cancellation is requested by the SDK itself (stop, unsubscribe or a newer heartbeat), not a failure.
if (status.category === categories_1.default.PNCancelledCategory)
return;
if (status.error && this.configuration.announceFailedHeartbeats)
this.emitStatus(status);
if (status.error && this.configuration.autoNetworkDetection && this.isOnline) {
Expand Down
7 changes: 6 additions & 1 deletion lib/core/pubnub-common.js
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,7 @@ class PubNubCore {
messageType: 'object',
message: Object.assign({}, parameters),
details: 'Heartbeat with parameters:',
ignoredKeys: ['crypto', 'timeout', 'keySet', 'getFileUrl'],
ignoredKeys: ['abortSignal', 'crypto', 'timeout', 'keySet', 'getFileUrl'],
}));
return this.heartbeat(parameters, callback);
}, (parameters, callback) => {
Expand Down Expand Up @@ -2083,6 +2083,11 @@ class PubNubCore {
if (abortUnsubscribe)
abortUnsubscribe();
return response;
}, (error) => {
// Detach on failure and cancellation too, not only on success.
if (abortUnsubscribe)
abortUnsubscribe();
throw error;
});
}
else
Expand Down
38 changes: 31 additions & 7 deletions lib/transport/middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
Object.defineProperty(exports, "__esModule", { value: true });
exports.PubNubMiddleware = void 0;
const transport_request_1 = require("../core/types/transport-request");
const pubnub_api_error_1 = require("../errors/pubnub-api-error");
const utils_1 = require("../core/utils");
/**
* Request signature generator.
Expand Down Expand Up @@ -101,25 +102,46 @@ class PubNubMiddleware {
if (retryPolicy !== undefined) {
let retryTimeout;
let activeCancellation;
let rejectRetry;
let canceled = false;
let settled = false;
let attempt = 0;
const rejectCancelled = () => {
if (settled)
return;
settled = true;
if (retryTimeout)
clearTimeout(retryTimeout);
const error = new Error('Aborted');
error.name = 'AbortError';
rejectRetry === null || rejectRetry === void 0 ? void 0 : rejectRetry(pubnub_api_error_1.PubNubAPIError.create(error));
};
const cancellation = {
abort: (reason) => {
canceled = true;
if (retryTimeout)
clearTimeout(retryTimeout);
// Settle before aborting the active attempt so a late success or another retry cannot win.
rejectCancelled();
if (activeCancellation)
activeCancellation.abort(reason);
},
};
const retryableRequest = new Promise((resolve, reject) => {
rejectRetry = reject;
const trySendRequest = () => {
// Check whether the request already has been canceled and there is no retry should proceed.
if (canceled)
// A retry callback can already be queued when cancel runs. Do not send it.
if (canceled || settled) {
rejectCancelled();
return;
}
const [attemptPromise, attemptCancellation] = transport.makeSendable(this.request(req));
activeCancellation = attemptCancellation;
const responseHandler = (res, error) => {
if (canceled || settled) {
rejectCancelled();
return;
}
let delay = -1;
// Retry ability (error category, HTTP status code, excluded endpoints and attempts count) is entirely
// decided by the retry policy.
Expand All @@ -130,11 +152,13 @@ class PubNubMiddleware {
this.logger.warn('PubNubMiddleware', `HTTP request retry #${attempt} in ${delay}ms.`);
retryTimeout = setTimeout(() => trySendRequest(), delay);
}
else {
if (res)
resolve(res);
else if (error)
reject(error);
else if (res) {
settled = true;
resolve(res);
}
else if (error) {
settled = true;
reject(error);
}
};
attemptPromise
Expand Down
11 changes: 10 additions & 1 deletion lib/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3110,9 +3110,18 @@ declare namespace PubNub {
* - `set presence state`
* - `here now`
* - `where now`
* - `heartbeat`
* - `leave`
*
* **Note:** `heartbeat` isn't part of this group. Use {@link Endpoint.PresenceHeartbeat} to control its retry.
*/
Presence = 'PresenceEndpoint',
/**
* The endpoint to announce `user_id` presence on channels and channel groups.
*
* This is related to the following functionality:
* - `heartbeat`
*/
PresenceHeartbeat = 'PresenceHeartbeatEndpoint',
/**
* The endpoint to access and manage files in channel-specific storage.
*
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions src/core/components/abort_signal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,16 @@ export class AbortError extends Error {
export class AbortSignal extends Subject<AbortError> {
private _aborted = false;

/**
* Notify listeners inside `abort()`.
*
* Managed-effect cancellation has to stop an in-flight request, including a retry that is only
* waiting, before the state machine dispatches the next effect.
*/
constructor() {
super(true);
}

get aborted() {
return this._aborted;
}
Expand Down
1 change: 1 addition & 0 deletions src/core/components/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ export const makeConfiguration = (
): PrivateClientConfiguration & PrivateConfigurationFields => {
// Set the default retry policy for subscribing (if new subscribe logic not used).
if (!base.retryConfiguration && base.enableEventEngine) {
// Only `Endpoint.Subscribe` and `Endpoint.PresenceHeartbeat` are retried by default.
base.retryConfiguration = RetryPolicy.ExponentialRetryPolicy({
minimumDelay: 2,
maximumDelay: 150,
Expand Down
23 changes: 22 additions & 1 deletion src/core/components/retry-policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,16 @@ import StatusCategory from '../constants/categories';
*/
const NON_RETRIABLE_STATUS_CODES = [404, 409];

/**
* Presence heartbeat request path.
*
* Matched strictly so `here now` for a channel named `heartbeat` or `get presence state` for a `heartbeat` user ID stay
* in {@link Endpoint.Presence}. The channel segment can be empty or `,` when only channel groups are used.
*
* @internal
*/
const HEARTBEAT_PATH = /^\/v2\/presence\/sub-key\/[^/]+\/channel\/[^/]*\/heartbeat$/;

// --------------------------------------------------------
// ------------------------ Types -------------------------
// --------------------------------------------------------
Expand Down Expand Up @@ -55,10 +65,20 @@ export enum Endpoint {
* - `set presence state`
* - `here now`
* - `where now`
* - `heartbeat`
* - `leave`
*
* **Note:** `heartbeat` isn't part of this group. Use {@link Endpoint.PresenceHeartbeat} to control its retry.
*/
Presence = 'PresenceEndpoint',

/**
* The endpoint to announce `user_id` presence on channels and channel groups.
*
* This is related to the following functionality:
* - `heartbeat`
*/
PresenceHeartbeat = 'PresenceHeartbeatEndpoint',

/**
* The endpoint to access and manage files in channel-specific storage.
*
Expand Down Expand Up @@ -367,6 +387,7 @@ const endpointFromRequest = (req: TransportRequest) => {

if (req.path.startsWith('/v2/subscribe')) endpoint = Endpoint.Subscribe;
else if (req.path.startsWith('/publish/') || req.path.startsWith('/signal/')) endpoint = Endpoint.MessageSend;
else if (HEARTBEAT_PATH.test(req.path)) endpoint = Endpoint.PresenceHeartbeat;
else if (req.path.startsWith('/v2/presence')) endpoint = Endpoint.Presence;
else if (req.path.startsWith('/v2/history') || req.path.startsWith('/v3/history')) endpoint = Endpoint.MessageStorage;
else if (req.path.startsWith('/v1/message-actions/')) endpoint = Endpoint.MessageReactions;
Expand Down
Loading
Loading