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: Fetch subscriptions for a user in get_streams_for_user.

Evy Kassirereb7eaba52608
diff --git a/web/src/peer_data.ts b/web/src/peer_data.ts
index bb4fb3a7c9a..38429f94eea 100644
--- a/web/src/peer_data.ts
+++ b/web/src/peer_data.ts
@@ -16,6 +16,8 @@ import * as util from "./util.ts";
// its count being accurate.
const subscriber_counts = new Map<number, number>();
+const fetched_user_subscriptions = new Set<number>();
+
// This maps a stream_id to a LazySet of user_ids who are subscribed.
// We might not have all the subscribers for a given stream. Streams
// with full data will be stored in `fetched_stream_ids`, and for the
@@ -30,6 +32,17 @@ const fetched_stream_ids = new Set<number>();
export function has_full_subscriber_data(stream_id: number): boolean {
return fetched_stream_ids.has(stream_id);
}
+
+// Don't run this in loops, since it has O(channels) runtime.
+export function has_complete_subscriber_data(): boolean {
+ const all_stream_ids = new Set(sub_store.stream_ids());
+ return (
+ all_stream_ids.size === fetched_stream_ids.size &&
+ all_stream_ids.difference(fetched_stream_ids).size === 0
+ );
+}
+
+// Requests for subscribers of a stream
const pending_subscriber_requests = new Map<
number,
{
@@ -40,17 +53,25 @@ const pending_subscriber_requests = new Map<
}[];
}
>();
+// Requests for subscriptions for a user
+const pending_subscription_requests = new Map<number, Promise<void>>();
export function clear_for_testing(): void {
stream_subscribers.clear();
fetched_stream_ids.clear();
pending_subscriber_requests.clear();
+ pending_subscription_requests.clear();
+ fetched_user_subscriptions.clear();
}
const fetch_stream_subscribers_response_schema = z.object({
subscribers: z.array(z.number()),
});
+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.
@@ -453,3 +474,67 @@ 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 load_subscriptions_for_user_with_retry(
+ user_id: number,
+ num_attempts = 0,
+): Promise<void> {
+ const subscriptions_promise = (async () => {
+ await channel.get({
+ url: `/json/users/${user_id}/channels`,
+ success(raw_data) {
+ const subscriptions =
+ fetch_user_subscriptions_response_schema.parse(raw_data).subscribed_channel_ids;
+ for (const stream_id of subscriptions) {
+ add_subscriber(stream_id, user_id);
+ }
+ fetched_user_subscriptions.add(user_id);
+ },
+ error(xhr) {
+ if (xhr.status === 400) {
+ blueslip.error("Bad request to fetch user's subscribed channels.", {
+ user_id,
+ });
+ return;
+ }
+ pending_subscription_requests.delete(user_id);
+ if (num_attempts === 5) {
+ blueslip.error("Failure fetching user's subscribed channels. Giving up.", {
+ user_id,
+ });
+ return;
+ }
+ 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 load_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);
+}
+
+export async function load_subscriptions_for_user(user_id: number): Promise<void> {
+ if (subscriber_data_loaded_for_user(user_id)) {
+ return;
+ }
+
+ if (pending_subscription_requests.has(user_id)) {
+ return pending_subscription_requests.get(user_id)!;
+ }
+
+ return load_subscriptions_for_user_with_retry(user_id);
+}
diff --git a/web/src/stream_data.ts b/web/src/stream_data.ts
index 5e3ad84082b..cf72bfc3e31 100644
--- a/web/src/stream_data.ts
+++ b/web/src/stream_data.ts
@@ -391,10 +391,19 @@ export function muted_stream_ids(): number[] {
.map((sub) => sub.stream_id);
}
-export function get_streams_for_user(user_id: number): {
+export async function get_streams_for_user(user_id: number): Promise<{
+ subscribed: StreamSubscription[];
+ can_subscribe: StreamSubscription[];
+}> {
+ await peer_data.load_subscriptions_for_user(user_id);
+ return get_fetched_streams_for_user(user_id);
+}
+
+export function get_fetched_streams_for_user(user_id: number): {
subscribed: StreamSubscription[];
can_subscribe: StreamSubscription[];
} {
+ assert(peer_data.subscriber_data_loaded_for_user(user_id));
// Note that we only have access to subscribers of some streams
// depending on our role.
const all_subs = get_unsorted_subs();
@@ -407,8 +416,6 @@ export function get_streams_for_user(user_id: number): {
// subscribers (which would trigger a warning).
continue;
}
- // TODO: Before calling this, we should get this user's subscriptions
- // and add them to the peer_data's stream_subscribers. #35341
if (is_user_loaded_and_subscribed(sub.stream_id, user_id)) {
subscribed_subs.push(sub);
} else if (can_subscribe_user(sub, user_id)) {
diff --git a/web/src/sub_store.ts b/web/src/sub_store.ts
index c5b820921cf..95d353917e2 100644
--- a/web/src/sub_store.ts
+++ b/web/src/sub_store.ts
@@ -32,6 +32,10 @@ export type StreamSubscription = z.infer<typeof stream_subscription_schema>;
const subs_by_stream_id = new Map<number, StreamSubscription>();
+export function stream_ids(): number[] {
+ return [...subs_by_stream_id.keys()];
+}
+
export function get(stream_id: number): StreamSubscription | undefined {
return subs_by_stream_id.get(stream_id);
}
diff --git a/web/src/user_profile.ts b/web/src/user_profile.ts
index c7b9efd34d3..94c100c187e 100644
--- a/web/src/user_profile.ts
+++ b/web/src/user_profile.ts
@@ -85,6 +85,7 @@ export type CustomProfileFieldData = {
let user_streams_list_widget: ListWidgetType<StreamSubscription> | undefined;
let user_groups_list_widget: ListWidgetType<UserGroup> | undefined;
let user_profile_subscribe_widget: DropdownWidget | undefined;
+let user_widget_current_user_id: number | undefined;
let user_group_pill_widget: user_group_pill.UserGroupPillWidget;
let toggler: components.Toggle;
let bot_owner_dropdown_widget: DropdownWidget | undefined;
@@ -124,11 +125,12 @@ export function get_user_id_if_user_profile_modal_open(): number | undefined {
export function update_user_profile_streams_list_for_users(user_ids: number[]): void {
const user_id = get_user_id_if_user_profile_modal_open();
if (user_id && user_ids.includes(user_id) && user_streams_list_widget !== undefined) {
- const user_streams = stream_data.get_streams_for_user(user_id).subscribed;
+ // The stream data should already be fetched for an open stream list widget.
+ const user_streams = stream_data.get_fetched_streams_for_user(user_id).subscribed;
user_streams.sort(compare_by_name);
user_streams_list_widget.replace_list_data(user_streams);
const user = people.get_by_user_id(user_id);
- render_or_update_user_streams_tab(user);
+ void render_or_update_user_streams_tab(user);
}
}
@@ -217,15 +219,18 @@ function initialize_bot_owner(
return user_pills;
}
-function render_user_profile_subscribe_widget(): void {
+function render_user_profile_subscribe_widget(user_id: number): void {
const opts: DropdownWidgetOptions = {
widget_name: "user_profile_subscribe",
- get_options: get_user_unsub_streams_for_dropdown,
+ // The stream data should already be fetched before calling the render
+ // function, since it's used for checking if we should render it.
+ get_options: get_fetched_user_unsub_streams_for_dropdown,
item_click_callback: change_state_of_subscribe_button,
$events_container: $("#user-profile-modal"),
unique_id_type: "number",
};
user_profile_subscribe_widget = new dropdown_widget.DropdownWidget(opts);
+ user_widget_current_user_id = user_id;
user_profile_subscribe_widget.setup();
}
@@ -257,14 +262,19 @@ function reset_subscribe_widget(): void {
}
}
-export function get_user_unsub_streams_for_dropdown(): dropdown_widget.Option[] {
+export function get_fetched_user_unsub_streams_for_dropdown(): dropdown_widget.Option[] {
const target_user_id = Number.parseInt($("#user-profile-modal").attr("data-user-id")!, 10);
- return get_user_unsub_streams(target_user_id);
+ return get_fetched_user_unsub_streams(target_user_id);
}
-export function get_user_unsub_streams(user_id: number): dropdown_widget.Option[] {
+async function get_user_unsub_streams(user_id: number): Promise<dropdown_widget.Option[]> {
+ await stream_data.get_streams_for_user(user_id);
+ return get_fetched_user_unsub_streams(user_id);
+}
+
+function get_fetched_user_unsub_streams(user_id: number): dropdown_widget.Option[] {
return stream_data
- .get_streams_for_user(user_id)
+ .get_fetched_streams_for_user(user_id)
.can_subscribe.map((stream) => ({
name: stream.name,
unique_id: stream.stream_id,
@@ -329,9 +339,24 @@ function format_user_group_list_item_html(group: UserGroup, user: User): string
});
}
-function render_or_update_user_streams_tab(user: User): void {
+async function render_or_update_user_streams_tab(user: User): Promise<void> {
+ if (!peer_data.subscriber_data_loaded_for_user(user.user_id)) {
+ $("#user-profile-streams-tab .stream-list-bottom-section").hide();
+ loading.make_indicator($(".stream-list-loader"), {
+ height: 56, // 4em at 14px / 1em
+ });
+ }
+ const user_streams = (await stream_data.get_streams_for_user(user.user_id)).subscribed;
+ const user_unsub_streams = await get_user_unsub_streams(user.user_id);
+ // If a modal for another user was opened while we were fetching data, there's
+ // nothing for us to do here.
+ if (user_widget_current_user_id !== undefined && user_widget_current_user_id !== user.user_id) {
+ return;
+ }
+
+ loading.destroy_indicator($(".stream-list-loader"));
+
if (!user_streams_list_widget) {
- const user_streams = stream_data.get_streams_for_user(user.user_id).subscribed;
render_user_stream_list(user_streams, user);
}
// We only show the subscribe widget if the user is an admin, the user has opened
@@ -341,7 +366,6 @@ function render_or_update_user_streams_tab(user: User): void {
// for that condition.
// We also don't show the widget if there are no channels the user is currently
// unsubscribed from and could become subscribed to (i.e. nothing to show in the widget).
- const user_unsub_streams = get_user_unsub_streams(user.user_id);
const show_user_subscribe_widget =
(people.can_admin_user(user) || current_user.is_admin) &&
user_unsub_streams.length > 0 &&
@@ -350,7 +374,7 @@ function render_or_update_user_streams_tab(user: User): void {
if (show_user_subscribe_widget && user_profile_subscribe_widget === undefined) {
reset_subscribe_widget();
- render_user_profile_subscribe_widget();
+ render_user_profile_subscribe_widget(user.user_id);
}
if (show_user_subscribe_widget) {
@@ -364,6 +388,7 @@ function render_user_stream_list(streams: StreamSubscription[], user: User): voi
streams.sort(compare_by_name);
const $container = $("#user-profile-modal .user-stream-list");
$container.empty();
+ user_widget_current_user_id = user.user_id;
user_streams_list_widget = ListWidget.create($container, streams, {
name: `user-${user.user_id}-stream-list`,
get_item: ListWidget.default_get_item,
@@ -408,6 +433,7 @@ function render_user_group_list(groups: UserGroup[], user: User): void {
groups.sort(compare_by_name);
const $container = $("#user-profile-modal .user-group-list");
$container.empty();
+ user_widget_current_user_id = user.user_id;
user_groups_list_widget = ListWidget.create($container, groups, {
name: `user-${user.user_id}-group-list`,
get_item: ListWidget.default_get_item,
@@ -650,6 +676,7 @@ export function show_user_profile(user: User, default_tab_key = "profile-tab"):
user_streams_list_widget = undefined;
user_groups_list_widget = undefined;
user_profile_subscribe_widget = undefined;
+ user_widget_current_user_id = undefined;
const field_types = realm.custom_profile_field_types;
const profile_data = realm.custom_profile_fields
@@ -741,7 +768,7 @@ export function show_user_profile(user: User, default_tab_key = "profile-tab"):
break;
}
case "user-profile-streams-tab": {
- render_or_update_user_streams_tab(user);
+ void render_or_update_user_streams_tab(user);
break;
}
case "manage-profile-tab":
diff --git a/web/styles/popovers.css b/web/styles/popovers.css
index ac63b29193a..992cfd11053 100644
--- a/web/styles/popovers.css
+++ b/web/styles/popovers.css
@@ -567,6 +567,10 @@ ul.popover-group-menu-member-list {
margin-bottom: 8px;
}
+ .stream-list-loader {
+ margin: 10px auto;
+ }
+
.stream-list-bottom-section,
.group-list-bottom-section {
grid-area: bottom;
diff --git a/web/templates/user_profile_modal.hbs b/web/templates/user_profile_modal.hbs
index 8018f78b445..69fc71cb53e 100644
--- a/web/templates/user_profile_modal.hbs
+++ b/web/templates/user_profile_modal.hbs
@@ -122,6 +122,7 @@
<i class="zulip-icon zulip-icon-close" aria-hidden="true"></i>
</button>
</div>
+ <div class="stream-list-loader"></div>
<div class="subscription-stream-list" data-simplebar data-simplebar-tab-index="-1">
<ul class="user-stream-list" data-empty="{{t 'No channel subscriptions.' }}" data-search-results-empty="{{t 'No matching channels.' }}"></ul>
</div>
diff --git a/web/tests/peer_data.test.cjs b/web/tests/peer_data.test.cjs
index 2db7733c43c..466be212d36 100644
--- a/web/tests/peer_data.test.cjs
+++ b/web/tests/peer_data.test.cjs
@@ -527,3 +527,84 @@ test("get_unique_subscriber_count_for_streams", async () => {
assert.equal(count, 2);
});
+
+test("load_subscriptions_for_user", async () => {
+ people.add_active_user(fred);
+
+ const india = {
+ stream_id: 102,
+ name: "India",
+ subscribed: true,
+ };
+ stream_data.add_sub_for_tests(india);
+ const rome = {name: "Rome", subscribed: true, stream_id: 1001};
+ stream_data.add_sub_for_tests(rome);
+
+ let channel_get_calls = 0;
+ channel.get = (opts) => {
+ assert.equal(opts.url, `/json/users/${fred.user_id}/channels`);
+ channel_get_calls += 1;
+ return {
+ 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.
+ const promise1 = peer_data.load_subscriptions_for_user(fred.user_id);
+ const promise2 = peer_data.load_subscriptions_for_user(fred.user_id);
+ await promise1;
+ await promise2;
+ 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);
+ blueslip.expect("error", "Failure fetching user's subscribed channels. Giving up.");
+ await peer_data.load_subscriptions_for_user(fred.user_id);
+ blueslip.reset();
+
+ peer_data.clear_for_testing();
+ channel.get = (payload) => {
+ payload.error({status: 400});
+ };
+ blueslip.expect("error", "Bad request to fetch user's subscribed channels.");
+ await peer_data.load_subscriptions_for_user(fred.user_id);
+ blueslip.reset();
+
+ 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) => {
+ if (error_counter === 3) {
+ payload.success({
+ subscribed_channel_ids: [india.stream_id],
+ });
+ } else {
+ error_counter += 1;
+ payload.error({status: 500});
+ }
+ };
+ blueslip.expect("warn", "Failure fetching user's subscribed channels. Retrying.", 3);
+ await peer_data.load_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 = () => {
+ channel_get_calls += 1;
+ return {
+ subscribers: [fred.user_id],
+ };
+ };
+ await peer_data.maybe_fetch_stream_subscribers(india.stream_id);
+ await peer_data.maybe_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.
+ await peer_data.load_subscriptions_for_user(fred.user_id);
+ assert.equal(channel_get_calls, 2);
+});
diff --git a/web/tests/stream_data.test.cjs b/web/tests/stream_data.test.cjs
index 0d6b64b3ab6..49b111733ed 100644
--- a/web/tests/stream_data.test.cjs
+++ b/web/tests/stream_data.test.cjs
@@ -25,6 +25,7 @@ const user_groups = zrequire("user_groups");
const {initialize_user_settings} = zrequire("user_settings");
const bot_data = mock_esm("../src/bot_data");
+const channel = mock_esm("../src/channel");
const current_user = {};
set_current_user(current_user);
@@ -136,7 +137,7 @@ function test(label, f) {
me_group,
],
});
- f(helpers);
+ return f(helpers);
});
}
@@ -523,7 +524,11 @@ test("basics", () => {
]);
});
-test("get_streams_for_user", ({override}) => {
+test("get_streams_for_user", async ({override}) => {
+ channel.get = (payload) =>
+ payload.success({
+ subscribed_channel_ids: [],
+ });
const denmark = {
subscribed: true,
color: "blue",
@@ -596,7 +601,10 @@ test("get_streams_for_user", ({override}) => {
peer_data.set_subscribers(world.stream_id, [me.user_id]);
override(realm, "realm_can_add_subscribers_group", students.id);
- assert.deepEqual(stream_data.get_streams_for_user(me.user_id).can_subscribe, [social, errors]);
+ assert.deepEqual((await stream_data.get_streams_for_user(me.user_id)).can_subscribe, [
+ social,
+ errors,
+ ]);
// test_user is subscribed to all three streams, but current user (me)
// gets only two because of subscriber visibility policy of stream:
@@ -605,24 +613,24 @@ test("get_streams_for_user", ({override}) => {
// user is a guest.
// #test: current user is no longer subscribed to a private stream, so
// he cannot see whether test_user is subscribed to it.
- assert.deepEqual(stream_data.get_streams_for_user(test_user.user_id).subscribed, [
+ assert.deepEqual((await stream_data.get_streams_for_user(test_user.user_id)).subscribed, [
denmark,
social,
]);
- assert.deepEqual(stream_data.get_streams_for_user(test_user.user_id).can_subscribe, []);
+ assert.deepEqual((await stream_data.get_streams_for_user(test_user.user_id)).can_subscribe, []);
// Administrator is not part of the realm_can_add_subscribers_group
// or the stream level can_add_subscribers_group. But users with
// the permission to administer a channel can also subscribe other
// users. Admins can administer all channels they have access to.
override(current_user, "is_admin", true);
assert.equal(user_groups.is_user_in_group(students.id, current_user.user_id), false);
- assert.deepEqual(stream_data.get_streams_for_user(test_user.user_id).can_subscribe, [
+ assert.deepEqual((await stream_data.get_streams_for_user(test_user.user_id)).can_subscribe, [
world,
errors,
]);
override(realm, "realm_can_add_subscribers_group", everyone_group.id);
- assert.deepEqual(stream_data.get_streams_for_user(test_user.user_id).can_subscribe, [
+ assert.deepEqual((await stream_data.get_streams_for_user(test_user.user_id)).can_subscribe, [
world,
errors,
]);