Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: subscribe timeout rejection #5427

Merged
merged 4 commits into from
Oct 8, 2024
Merged
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
21 changes: 19 additions & 2 deletions packages/core/src/controllers/relayer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,12 @@ export class Relayer extends IRelayer {
if (opts?.transportType === "relay") {
await this.toEstablishConnection();
}
// throw unless explicitly set to false
const shouldThrowOnFailure =
typeof opts?.internal?.throwOnFailedPublish === "undefined"
? true
: opts?.internal?.throwOnFailedPublish;

let id = this.subscriber.topicMap.get(topic)?.[0] || "";
let resolvePromise: () => void;
const onSubCreated = (subscription: SubscriberTypes.Active) => {
Expand All @@ -181,8 +187,19 @@ export class Relayer extends IRelayer {
resolvePromise = resolve;
this.subscriber.on(SUBSCRIBER_EVENTS.created, onSubCreated);
}),
new Promise<void>(async (resolve) => {
const result = await this.subscriber.subscribe(topic, opts);
new Promise<void>(async (resolve, reject) => {
const result = await this.subscriber
.subscribe(topic, {
internal: {
throwOnFailedPublish: shouldThrowOnFailure,
},
...opts,
ganchoradkov marked this conversation as resolved.
Show resolved Hide resolved
})
.catch((error) => {
if (shouldThrowOnFailure) {
reject(error);
}
});
id = result || id;
resolve();
}),
Expand Down
16 changes: 9 additions & 7 deletions packages/core/src/controllers/subscriber.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@
const relay = getRelayProtocolName(opts);
const params = { topic, relay, transportType: opts?.transportType };
this.pending.set(topic, params);
const id = await this.rpcSubscribe(topic, relay, opts?.transportType);
const id = await this.rpcSubscribe(topic, relay, opts);
if (typeof id === "string") {
this.onSubscribe(id, params);
this.logger.debug(`Successfully Subscribed Topic`);
Expand Down Expand Up @@ -222,9 +222,9 @@
private async rpcSubscribe(
topic: string,
relay: RelayerTypes.ProtocolOptions,
transportType: RelayerTypes.TransportType = TRANSPORT_TYPES.relay,
opts?: RelayerTypes.SubscribeOptions,
) {
if (transportType === TRANSPORT_TYPES.relay) {
if (opts?.transportType === TRANSPORT_TYPES.relay) {
await this.restartToComplete();
}
const api = getRelayProtocolApi(relay.protocol);
Expand All @@ -239,26 +239,28 @@
try {
const subId = hashMessage(topic + this.clientId);
// in link mode, allow the app to update its network state (i.e. active airplane mode) with small delay before attempting to subscribe
if (transportType === TRANSPORT_TYPES.link_mode) {
if (opts?.transportType === TRANSPORT_TYPES.link_mode) {
setTimeout(() => {
if (this.relayer.connected || this.relayer.connecting) {
this.relayer.request(request).catch((e) => this.logger.warn(e));
}
}, toMiliseconds(ONE_SECOND));
return subId;
}

const subscribe = await createExpiringPromise(
const subscribe = createExpiringPromise(
this.relayer.request(request).catch((e) => this.logger.warn(e)),
this.subscribeTimeout,
`Subscribing to ${topic} failed, please try again`,
);
const result = await subscribe;

// return null to indicate that the subscription failed
return result ? subId : null;
} catch (err) {
this.logger.debug(`Outgoing Relay Subscribe Payload stalled`);
this.relayer.events.emit(RELAYER_EVENTS.connection_stalled);
if (opts?.internal?.throwOnFailedPublish) {
throw err;
}
}
return null;
}
Expand All @@ -266,7 +268,7 @@
private async rpcBatchSubscribe(subscriptions: SubscriberTypes.Params[]) {
if (!subscriptions.length) return;
const relay = subscriptions[0].relay;
const api = getRelayProtocolApi(relay!.protocol);

Check warning on line 271 in packages/core/src/controllers/subscriber.ts

View workflow job for this annotation

GitHub Actions / code_style (lint)

Forbidden non-null assertion
const request: RequestArguments<RelayJsonRpc.BatchSubscribeParams> = {
method: api.batchSubscribe,
params: {
Expand All @@ -289,7 +291,7 @@
private async rpcBatchFetchMessages(subscriptions: SubscriberTypes.Params[]) {
if (!subscriptions.length) return;
const relay = subscriptions[0].relay;
const api = getRelayProtocolApi(relay!.protocol);

Check warning on line 294 in packages/core/src/controllers/subscriber.ts

View workflow job for this annotation

GitHub Actions / code_style (lint)

Forbidden non-null assertion
const request: RequestArguments<RelayJsonRpc.BatchFetchMessagesParams> = {
method: api.batchFetchMessages,
params: {
Expand Down
42 changes: 33 additions & 9 deletions packages/core/test/relayer.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { expect, describe, it, beforeEach, afterEach } from "vitest";
import { expect, describe, it, beforeEach, afterEach, vi } from "vitest";
import { getDefaultLoggerOptions, pino } from "@walletconnect/logger";
import { JsonRpcProvider } from "@walletconnect/jsonrpc-provider";

Expand Down Expand Up @@ -125,16 +125,20 @@ describe("Relayer", () => {
projectId: TEST_CORE_OPTIONS.projectId,
});
await relayer.init();
await relayer.transportOpen();
});
afterEach(async () => {
await disconnectSocket(relayer);
});

it("returns the id provided by calling `subscriber.subscribe` with the passed topic", async () => {
const spy = Sinon.spy((topic) => {
relayer.subscriber.events.emit(SUBSCRIBER_EVENTS.created, { topic });
return topic;
});
const spy = Sinon.spy(
(topic) =>
new Promise((resolve) => {
relayer.subscriber.events.emit(SUBSCRIBER_EVENTS.created, { topic });
resolve(topic);
}),
);
relayer.subscriber.subscribe = spy;

const testTopic = "abc123";
Expand All @@ -149,10 +153,13 @@ describe("Relayer", () => {
});

it("should subscribe multiple topics", async () => {
const spy = Sinon.spy((topic) => {
relayer.subscriber.events.emit(SUBSCRIBER_EVENTS.created, { topic });
return topic;
});
const spy = Sinon.spy(
(topic) =>
new Promise((resolve) => {
relayer.subscriber.events.emit(SUBSCRIBER_EVENTS.created, { topic });
resolve(topic);
}),
);
relayer.subscriber.subscribe = spy;
const subscriber = relayer.subscriber as ISubscriber;
// record the number of listeners before subscribing
Expand All @@ -164,6 +171,23 @@ describe("Relayer", () => {
expect(subscriber.events.listenerCount(SUBSCRIBER_EVENTS.created)).to.eq(startNumListeners);
});

it("should throw when subscribe reaches a publish timeout", async () => {
await relayer.transportOpen();
await relayer.toEstablishConnection();
relayer.subscriber.subscribeTimeout = 5_000;
relayer.request = () => {
return new Promise<void>((_, reject) => {
setTimeout(() => {
reject(new Error("Subscription timeout"));
}, 100_000);
});
};
const topic = generateRandomBytes32();
await expect(relayer.subscribe(topic)).rejects.toThrow(
`Subscribing to ${topic} failed, please try again`,
);
});

it("should be able to resubscribe on topic that already exists", async () => {
const topic = generateRandomBytes32();
const id = await relayer.subscribe(topic);
Expand Down
3 changes: 3 additions & 0 deletions packages/types/src/core/relayer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ export declare namespace RelayerTypes {
export interface SubscribeOptions {
relay?: ProtocolOptions;
transportType?: TransportType;
internal?: {
throwOnFailedPublish?: boolean;
};
}

export interface UnsubscribeOptions {
Expand Down
Loading