Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

peer_data: Fix data fetches to handle errors more specifically.

Evy Kassirereb4ea4c1a0d2
diff --git a/web/src/peer_data.ts b/web/src/peer_data.ts
index d1de9cc67b4..c23c9840ce2 100644
--- a/web/src/peer_data.ts
+++ b/web/src/peer_data.ts
@@ -46,7 +46,8 @@ export function has_complete_subscriber_data(): boolean {
const pending_subscriber_requests = new Map<
number,
{
- subscribers_promise: Promise<LazySet | null>;
+ // false means bad request, null means we retried too many times and gave up
+ subscribers_promise: Promise<LazySet | null | false>;
pending_peer_events: {
type: "peer_add" | "peer_remove";
user_ids: number[];
@@ -72,60 +73,87 @@ const fetch_user_subscriptions_response_schema = z.object({
subscribed_channel_ids: z.array(z.number()),
});
-// This function will always resolve to a LazySet but could hang
-// indefinitely trying to fetch data. `num_attempts` should only
-// be set in the recursive call.
-export async function maybe_fetch_stream_subscribers_with_retry(
+// Warning: This function can fetch indefinitely (with longer retry
+// delay each time) if the server keeps returning non-400 errors.
+export async function fetch_stream_subscribers_with_retry(
stream_id: number,
num_attempts = 1,
-): Promise<LazySet> {
+): Promise<LazySet | null> {
const subscribers = await fetch_stream_subscribers(stream_id);
+ // Bad request, so just give up here.
+ if (subscribers === false) {
+ return null;
+ }
+ // Failed request, retry.
if (subscribers === null) {
num_attempts += 1;
const retry_delay_secs = util.get_retry_backoff_seconds(undefined, num_attempts);
await new Promise((resolve) => setTimeout(resolve, retry_delay_secs * 1000));
- return maybe_fetch_stream_subscribers_with_retry(stream_id, num_attempts);
+ return fetch_stream_subscribers_with_retry(stream_id, num_attempts);
}
return subscribers;
}
-export async function fetch_stream_subscribers(stream_id: number): Promise<LazySet | null> {
+// This function either waits for an existing pending request or kicks off
+// a new one.
+export async function fetch_stream_subscribers(stream_id: number): Promise<LazySet | null | false> {
if (pending_subscriber_requests.has(stream_id)) {
return pending_subscriber_requests.get(stream_id)!.subscribers_promise;
}
- const subscribers_promise = (async () => {
- let subscribers: number[];
- try {
- const result = await channel.get({
- url: `/json/streams/${stream_id}/members`,
- });
- subscribers = fetch_stream_subscribers_response_schema.parse(result).subscribers;
- } catch {
- blueslip.error("Failure fetching channel subscribers", {
- stream_id,
- });
- pending_subscriber_requests.delete(stream_id);
- return null;
- }
-
- set_subscribers(stream_id, subscribers);
- const pending_peer_events = pending_subscriber_requests.get(stream_id)!.pending_peer_events;
- pending_subscriber_requests.delete(stream_id);
- for (const event of pending_peer_events) {
- if (event.type === "peer_add") {
- bulk_add_subscribers({stream_ids: [stream_id], user_ids: event.user_ids});
- } else {
- bulk_remove_subscribers({stream_ids: [stream_id], user_ids: event.user_ids});
- }
- }
- return get_loaded_subscriber_subset(stream_id);
- })();
-
pending_subscriber_requests.set(stream_id, {
- subscribers_promise,
+ subscribers_promise: fetch_stream_subscribers_from_server(stream_id),
pending_peer_events: [],
});
- return subscribers_promise;
+ return pending_subscriber_requests.get(stream_id)!.subscribers_promise;
+}
+
+// This function wraps the fetch in a Promise so that we can have both
+// the `channel.get` handling the xhr error and
+// `fetch_stream_subscribers_from_server` not resolving until the success/error
+// handling finishes.
+async function fetch_stream_subscribers_from_server(
+ stream_id: number,
+): Promise<LazySet | null | false> {
+ return new Promise<LazySet | null | false>((resolve) => {
+ void channel.get({
+ url: `/json/streams/${stream_id}/members`,
+ success(result) {
+ const fetched_subscribers =
+ fetch_stream_subscribers_response_schema.parse(result).subscribers;
+ set_subscribers(stream_id, fetched_subscribers);
+ const pending_peer_events =
+ pending_subscriber_requests.get(stream_id)!.pending_peer_events;
+ pending_subscriber_requests.delete(stream_id);
+ for (const event of pending_peer_events) {
+ if (event.type === "peer_add") {
+ bulk_add_subscribers({stream_ids: [stream_id], user_ids: event.user_ids});
+ } else {
+ bulk_remove_subscribers({
+ stream_ids: [stream_id],
+ user_ids: event.user_ids,
+ });
+ }
+ }
+
+ resolve(get_loaded_subscriber_subset(stream_id));
+ },
+ error(xhr) {
+ pending_subscriber_requests.delete(stream_id);
+ if (xhr.status === 400) {
+ blueslip.error("Bad request to fetch channel subscribers.", {
+ stream_id,
+ error_json: xhr.responseJSON,
+ });
+ resolve(false);
+ } else {
+ blueslip.error("Failure fetching channel subscribers", {
+ stream_id,
+ });
+ resolve(null);
+ }
+ },
+ });
+ });
}
function get_loaded_subscriber_subset(stream_id: number): LazySet {
@@ -160,14 +188,14 @@ async function get_full_subscriber_set(
// This function parallels `get_loaded_subscriber_subset` but ensures we include all
// subscribers, possibly fetching that data from the server.
if (!fetched_stream_ids.has(stream_id) && sub_store.get(stream_id)) {
- let fetched_subscribers: LazySet | null;
+ let fetched_subscribers: LazySet | null | false;
if (retry_on_failure) {
- fetched_subscribers = await maybe_fetch_stream_subscribers_with_retry(stream_id);
+ fetched_subscribers = await fetch_stream_subscribers_with_retry(stream_id);
} else {
fetched_subscribers = await fetch_stream_subscribers(stream_id);
}
// This means a request failed and we don't know who the subscribers are.
- if (fetched_subscribers === null) {
+ if (fetched_subscribers === null || fetched_subscribers === false) {
return null;
}
set_subscribers(stream_id, [...fetched_subscribers.keys()]);
@@ -475,14 +503,12 @@ export async function get_unique_subscriber_count_for_streams(
return valid_subscribers.size;
}
-// This function might retry up to 5 times to fetch data, then will
-// give up. `num_attempts` should only be set in the recursive call.
-async function fetch_subscriptions_for_user_with_retry(
- user_id: number,
- num_attempts = 0,
-): Promise<void> {
- const subscriptions_promise = (async () => {
- await channel.get({
+// This function wraps the fetch in a Promise so that we can have both
+// the `channel.get` handling the xhr error and `load_subscriptions_for_user`
+// not resolving until the success/error handling finishes.
+async function fetch_subscriptions_for_user_from_server(user_id: number): Promise<boolean | null> {
+ return new Promise<boolean | null>((resolve) => {
+ channel.get({
url: `/json/users/${user_id}/channels`,
success(raw_data) {
const subscriptions =
@@ -491,42 +517,26 @@ async function fetch_subscriptions_for_user_with_retry(
add_subscriber(stream_id, user_id);
}
fetched_user_subscriptions.add(user_id);
+ resolve(true);
},
error(xhr) {
if (xhr.status === 400) {
blueslip.error("Bad request to fetch user's subscribed channels.", {
user_id,
+ error_json: xhr.responseJSON,
});
- return;
- }
- pending_subscription_requests.delete(user_id);
- if (num_attempts === 5) {
- blueslip.error("Failure fetching user's subscribed channels. Giving up.", {
- user_id,
- });
- return;
+ resolve(false);
+ } else {
+ resolve(null);
}
- blueslip.warn("Failure fetching user's subscribed channels. Retrying.", {
- user_id,
- });
- num_attempts += 1;
- const retry_delay_secs = util.get_retry_backoff_seconds(undefined, num_attempts);
- setTimeout(() => {
- void fetch_subscriptions_for_user_with_retry(user_id, num_attempts);
- }, retry_delay_secs * 1000);
- return;
},
});
- })();
-
- pending_subscription_requests.set(user_id, subscriptions_promise);
- return subscriptions_promise;
-}
-
-export function subscriber_data_loaded_for_user(user_id: number): boolean {
- return has_complete_subscriber_data() || fetched_user_subscriptions.has(user_id);
+ });
}
+// This function might retry up to 5 times to fetch data, then will give up.
+// We store the whole fetch with retry promise in the pending requests because
+// there are no outside calls to fetch_subscriptions_for_user (without retry).
export async function fetch_subscriptions_for_user(user_id: number): Promise<void> {
if (subscriber_data_loaded_for_user(user_id)) {
return;
@@ -536,5 +546,44 @@ export async function fetch_subscriptions_for_user(user_id: number): Promise<voi
return pending_subscription_requests.get(user_id)!;
}
- return fetch_subscriptions_for_user_with_retry(user_id);
+ const subscriptions_promise = (async () => {
+ let num_attempts = 0;
+ while (num_attempts < 5) {
+ if (num_attempts > 0) {
+ blueslip.warn("Failure fetching user's subscribed channels. Retrying.", {
+ user_id,
+ });
+ }
+ const result = await fetch_subscriptions_for_user_from_server(user_id);
+ // Bad request, so just give up here.
+ if (result === false) {
+ pending_subscription_requests.delete(user_id);
+ break;
+ }
+ // Failed request, so try again (unless we've reached the retry limit)
+ else if (result === null) {
+ num_attempts += 1;
+ const retry_delay_secs = util.get_retry_backoff_seconds(undefined, num_attempts);
+ await new Promise((resolve) => setTimeout(resolve, retry_delay_secs * 1000));
+ continue;
+ }
+ // Success
+ else {
+ pending_subscription_requests.delete(user_id);
+ break;
+ }
+ }
+ if (num_attempts === 5) {
+ blueslip.error("Failure fetching user's subscribed channels. Giving up.", {
+ user_id,
+ });
+ }
+ })();
+
+ pending_subscription_requests.set(user_id, subscriptions_promise);
+ return subscriptions_promise;
+}
+
+export function subscriber_data_loaded_for_user(user_id: number): boolean {
+ return has_complete_subscriber_data() || fetched_user_subscriptions.has(user_id);
}
diff --git a/web/tests/compose_validate.test.cjs b/web/tests/compose_validate.test.cjs
index 6a0fc80a8a3..a2d883f4a63 100644
--- a/web/tests/compose_validate.test.cjs
+++ b/web/tests/compose_validate.test.cjs
@@ -7,6 +7,7 @@ const {FakeComposeBox} = require("./lib/compose_helpers.cjs");
const {make_user_group} = require("./lib/example_group.cjs");
const {make_realm} = require("./lib/example_realm.cjs");
const {$t} = require("./lib/i18n.cjs");
+const {mock_channel_get} = require("./lib/mock_channel.cjs");
const {mock_esm, zrequire} = require("./lib/namespace.cjs");
const {run_test, noop} = require("./lib/test.cjs");
const blueslip = require("./lib/zblueslip.cjs");
@@ -721,12 +722,12 @@ test_ui("warn_if_mentioning_unsubscribed_user", async ({override, mock_template}
new_banner_rendered = false;
const $banner_container = $("#compose_banners");
$banner_container.set_find_results(".recipient_not_subscribed", []);
- channel.get = (opts) => {
+ mock_channel_get(channel, (opts) => {
assert.equal(opts.url, `/json/streams/${sub.stream_id}/members`);
- return {
+ return opts.success({
subscribers: [],
- };
- };
+ });
+ });
await compose_validate.warn_if_mentioning_unsubscribed_user(mentioned_details, $textarea);
assert.ok(new_banner_rendered);
diff --git a/web/tests/lib/mock_channel.cjs b/web/tests/lib/mock_channel.cjs
new file mode 100644
index 00000000000..c2464750c45
--- /dev/null
+++ b/web/tests/lib/mock_channel.cjs
@@ -0,0 +1,11 @@
+"use strict";
+
+// We have to pass channel here so that the test file mocks channel.ts before
+// tests start running, and so that channel.ts is only mocked once.
+exports.mock_channel_get = function (channel, f) {
+ channel.get = async (opts) => {
+ // await an empty promise to ensure the "fetch" happens asynchronously
+ await Promise.resolve();
+ f(opts);
+ };
+};
diff --git a/web/tests/peer_data.test.cjs b/web/tests/peer_data.test.cjs
index d18fd71412b..bee52f7b366 100644
--- a/web/tests/peer_data.test.cjs
+++ b/web/tests/peer_data.test.cjs
@@ -11,6 +11,7 @@ const assert = require("node:assert/strict");
const {make_user_group} = require("./lib/example_group.cjs");
const {make_realm} = require("./lib/example_realm.cjs");
const example_settings = require("./lib/example_settings.cjs");
+const {mock_channel_get} = require("./lib/mock_channel.cjs");
const {mock_esm, set_global, zrequire} = require("./lib/namespace.cjs");
const {run_test} = require("./lib/test.cjs");
const blueslip = require("./lib/zblueslip.cjs");
@@ -282,13 +283,13 @@ test("maybe_fetch_stream_subscribers", async () => {
};
stream_data.add_sub_for_tests(india);
let channel_get_calls = 0;
- channel.get = (opts) => {
+ mock_channel_get(channel, (opts) => {
assert.equal(opts.url, `/json/streams/${india.stream_id}/members`);
channel_get_calls += 1;
- return {
+ opts.success({
subscribers: [1, 2, 3, 4],
- };
- };
+ });
+ });
// Only one of these will do the fetch, and the other will wait
// for the first fetch to complete.
@@ -336,9 +337,21 @@ test("maybe_fetch_stream_subscribers", async () => {
);
peer_data.clear_for_testing();
- channel.get = () => {
- throw new Error("error");
- };
+ mock_channel_get(channel, (opts) => {
+ opts.error({status: 400, responseJSON: ""});
+ });
+ blueslip.expect("error", "Bad request to fetch channel subscribers.");
+ // retry is false, so we get null because there was an error
+ assert.deepEqual(
+ await peer_data.get_subscribers_with_possible_fetch(india.stream_id, false),
+ null,
+ );
+ blueslip.reset();
+
+ peer_data.clear_for_testing();
+ mock_channel_get(channel, (opts) => {
+ opts.error({status: 500, responseJSON: ""});
+ });
blueslip.expect("error", "Failure fetching channel subscribers");
// retry is false, so we get null because there was an error
assert.deepEqual(
@@ -347,18 +360,21 @@ test("maybe_fetch_stream_subscribers", async () => {
);
blueslip.reset();
- channel.get = () => {
- throw new Error("error");
- };
peer_data.clear_for_testing();
+ mock_channel_get(channel, (opts) => {
+ opts.error({status: 500, responseJSON: ""});
+ });
blueslip.expect("error", "Failure fetching channel subscribers");
assert.equal(await peer_data.maybe_fetch_is_user_subscribed(india.stream_id, 5, false), null);
+ blueslip.reset();
+
// If we know they're subscribed, we return `true` even though we don't have complete
// data.
peer_data.bulk_add_subscribers({
stream_ids: [india.stream_id],
user_ids: [5],
});
+ blueslip.expect("error", "Failure fetching channel subscribers");
assert.equal(await peer_data.maybe_fetch_is_user_subscribed(india.stream_id, 5, false), true);
blueslip.reset();
@@ -367,15 +383,16 @@ test("maybe_fetch_stream_subscribers", async () => {
f();
});
let num_attempts = 0;
- channel.get = async () => {
+ mock_channel_get(channel, (opts) => {
num_attempts += 1;
if (num_attempts === 2) {
- return {
+ opts.success({
subscribers: [1, 2, 3, 4],
- };
+ });
+ } else {
+ opts.error({status: 500, responseJSON: ""});
}
- throw new Error("error");
- };
+ });
blueslip.expect("error", "Failure fetching channel subscribers");
const subscribers = await peer_data.fetch_stream_subscribers_with_retry(india.stream_id);
assert.equal(num_attempts, 2);
@@ -387,6 +404,19 @@ test("maybe_fetch_stream_subscribers", async () => {
num_attempts = 0;
assert.equal(await peer_data.maybe_fetch_is_user_subscribed(india.stream_id, 5, true), false);
assert.equal(num_attempts, 2);
+
+ // No retry if it's a bad request
+ num_attempts = 0;
+ mock_channel_get(channel, (opts) => {
+ num_attempts += 1;
+ assert.equal(num_attempts, 1);
+ opts.error({status: 400, responseJSON: "bad request"});
+ });
+ peer_data.clear_for_testing();
+ blueslip.expect("error", "Bad request to fetch channel subscribers.");
+ await peer_data.fetch_stream_subscribers_with_retry(india.stream_id);
+ assert.equal(num_attempts, 1);
+ blueslip.reset();
});
test("get_subscriber_count", async () => {
@@ -437,8 +467,10 @@ test("get_subscriber_count", async () => {
assert.deepStrictEqual(peer_data.get_subscriber_count(india.stream_id), 19);
// Now fetch the actual subscribers
- channel.get = () => ({
- subscribers: [george.user_id, fred.user_id],
+ mock_channel_get(channel, (opts) => {
+ opts.success({
+ subscribers: [george.user_id, fred.user_id],
+ });
});
await peer_data.fetch_stream_subscribers(india.stream_id);
assert.deepStrictEqual(peer_data.get_subscriber_count(india.stream_id), 2);
@@ -502,9 +534,9 @@ test("is_subscriber_subset", async () => {
blueslip.reset();
// Errors when fetching subscriber data return `null`
- channel.get = () => {
- throw new Error("error");
- };
+ mock_channel_get(channel, (opts) => {
+ opts.error({status: 500});
+ });
peer_data.clear_for_testing();
// Expect two calls, one for each channel
blueslip.expect("error", "Failure fetching channel subscribers", 2);
@@ -541,13 +573,13 @@ test("fetch_subscriptions_for_user", async () => {
stream_data.add_sub_for_tests(rome);
let channel_get_calls = 0;
- channel.get = (opts) => {
+ mock_channel_get(channel, (opts) => {
assert.equal(opts.url, `/json/users/${fred.user_id}/channels`);
channel_get_calls += 1;
- return {
+ return opts.success({
subscribed_channel_ids: [india.stream_id],
- };
- };
+ });
+ });
// Only one of these will do the fetch, and the other will wait
// for the first fetch to complete.
@@ -558,18 +590,18 @@ test("fetch_subscriptions_for_user", async () => {
assert.equal(channel_get_calls, 1);
peer_data.clear_for_testing();
- channel.get = (payload) => {
- payload.error({status: 500});
- };
- blueslip.expect("warn", "Failure fetching user's subscribed channels. Retrying.", 5);
+ mock_channel_get(channel, (opts) => {
+ opts.error({status: 500});
+ });
+ blueslip.expect("warn", "Failure fetching user's subscribed channels. Retrying.", 4);
blueslip.expect("error", "Failure fetching user's subscribed channels. Giving up.");
await peer_data.fetch_subscriptions_for_user(fred.user_id);
blueslip.reset();
peer_data.clear_for_testing();
- channel.get = (payload) => {
- payload.error({status: 400});
- };
+ mock_channel_get(channel, (opts) => {
+ opts.error({status: 400, responseJSON: {msg: "bad request"}});
+ });
blueslip.expect("error", "Bad request to fetch user's subscribed channels.");
await peer_data.fetch_subscriptions_for_user(fred.user_id);
blueslip.reset();
@@ -577,34 +609,37 @@ test("fetch_subscriptions_for_user", async () => {
peer_data.clear_for_testing();
assert.ok(!stream_data.is_user_loaded_and_subscribed(india.stream_id, fred.user_id));
let error_counter = 0;
- channel.get = (payload) => {
+ mock_channel_get(channel, (opts) => {
if (error_counter === 3) {
- payload.success({
+ opts.success({
subscribed_channel_ids: [india.stream_id],
});
} else {
error_counter += 1;
- payload.error({status: 500});
+ opts.error({
+ status: 500,
+ });
}
- };
+ });
blueslip.expect("warn", "Failure fetching user's subscribed channels. Retrying.", 3);
await peer_data.fetch_subscriptions_for_user(fred.user_id);
assert.ok(stream_data.is_user_loaded_and_subscribed(india.stream_id, fred.user_id));
blueslip.reset();
channel_get_calls = 0;
- channel.get = () => {
+ mock_channel_get(channel, (opts) => {
channel_get_calls += 1;
- return {
+ opts.success({
subscribers: [fred.user_id],
- };
- };
+ });
+ });
await peer_data.fetch_stream_subscribers(india.stream_id);
await peer_data.fetch_stream_subscribers(rome.stream_id);
assert.equal(channel_get_calls, 2);
// No get request here because we already have full subscriber data
// for both streams.
+ channel_get_calls = 0;
await peer_data.fetch_subscriptions_for_user(fred.user_id);
- assert.equal(channel_get_calls, 2);
+ assert.equal(channel_get_calls, 0);
});
diff --git a/web/tests/user_search.test.cjs b/web/tests/user_search.test.cjs
index 70f9f128b40..454a32adc14 100644
--- a/web/tests/user_search.test.cjs
+++ b/web/tests/user_search.test.cjs
@@ -4,10 +4,13 @@ const assert = require("node:assert/strict");
const {make_realm} = require("./lib/example_realm.cjs");
const {make_message_list} = require("./lib/message_list.cjs");
+const {mock_channel_get} = require("./lib/mock_channel.cjs");
const {set_global, mock_esm, zrequire} = require("./lib/namespace.cjs");
const {run_test, noop} = require("./lib/test.cjs");
const $ = require("./lib/zjquery.cjs");
+const channel = mock_esm("../src/channel");
+
const fake_buddy_list = {
scroll_container_selector: "#whatever",
$users_matching_view_list: {
@@ -32,7 +35,6 @@ function mock_setTimeout() {
});
}
-const channel = mock_esm("../src/channel");
const popovers = mock_esm("../src/popovers");
const presence = mock_esm("../src/presence");
const sidebar_ui = mock_esm("../src/sidebar_ui");
@@ -153,12 +155,12 @@ test("fetch on search", async ({override}) => {
make_message_list([{operator: "stream", operand: office.stream_id.toString()}]),
);
let get_call_count = 0;
- channel.get = () => {
+ mock_channel_get(channel, (opts) => {
get_call_count += 1;
- return {
+ opts.success({
subscribers: [1, 2, 3, 4],
- };
- };
+ });
+ });
// Only one fetch should happen.
set_input_val("somevalu");
set_input_val("somevalue");