A platform for community discussion. Free, open, simple.
PERF: Load rewind reports asynchronously while scrolling (#36563)
Rafael dos Santos Silva174d32f9d968
diff --git a/plugins/discourse-rewind/app/controllers/discourse_rewind/rewinds_controller.rb b/plugins/discourse-rewind/app/controllers/discourse_rewind/rewinds_controller.rbindex b71d2ff3d5b..5c0a8b07548 100644--- a/plugins/discourse-rewind/app/controllers/discourse_rewind/rewinds_controller.rb+++ b/plugins/discourse-rewind/app/controllers/discourse_rewind/rewinds_controller.rb@@ -6,15 +6,37 @@ module ::DiscourseRewindrequires_login- def show+ def indexDiscourseRewind::FetchReports.call(service_params) doon_model_not_found(:year) doraise Discourse::NotFound.new(nil, custom_message: "discourse_rewind.invalid_year")end- on_model_not_found(:reports) do+ on_model_not_found(:all_reports) doraise Discourse::NotFound.new(nil, custom_message: "discourse_rewind.report_failed")end- on_success { |reports:| render json: MultiJson.dump(reports), status: :ok }+ on_success do |reports:, total_available:|+ render json: { reports:, total_available: }, status: :ok+ end+ end+ end++ def show+ DiscourseRewind::FetchReport.call(service_params) do+ on_model_not_found(:year) do+ raise Discourse::NotFound.new(nil, custom_message: "discourse_rewind.invalid_year")+ end+ on_model_not_found(:all_reports) do+ raise Discourse::NotFound.new(nil, custom_message: "discourse_rewind.reports_not_cached")+ end+ on_model_not_found(:report) do+ raise Discourse::NotFound.new(nil, custom_message: "discourse_rewind.report_not_found")+ end+ on_failed_contract do |contract|+ render json: failed_json.merge(errors: contract.errors.full_messages),+ status: :bad_request+ end+ on_failure { render(json: failed_json, status: :unprocessable_entity) }+ on_success { |report:| render json: { report: }, status: :ok }endendenddiff --git a/plugins/discourse-rewind/app/services/discourse_rewind/fetch_report.rb b/plugins/discourse-rewind/app/services/discourse_rewind/fetch_report.rbnew file mode 100644index 00000000000..312c033ec68--- /dev/null+++ b/plugins/discourse-rewind/app/services/discourse_rewind/fetch_report.rb@@ -0,0 +1,64 @@+# frozen_string_literal: true++module DiscourseRewind+ # Service responsible to fetch a single report by index.+ #+ # @example+ # ::DiscourseRewind::FetchReport.call(+ # guardian: guardian,+ # params: { index: 3 }+ # )+ #+ class FetchReport+ include Service::Base++ # @!method self.call(guardian:, params:)+ # @param [Guardian] guardian+ # @param [Hash] params+ # @option params [Integer] :index of the report+ # @return [Service::Base::Context]++ params do+ attribute :index, :integer++ validates :index, presence: true, numericality: { greater_than_or_equal_to: 0 }+ end++ model :year+ model :all_reports+ model :report++ private++ def fetch_year+ current_date = Time.zone.now+ current_month = current_date.month+ current_year = current_date.year++ case current_month+ when 1+ current_year - 1+ when 12+ current_year+ else+ if Rails.env.development?+ current_year+ else+ false+ end+ end+ end++ def fetch_all_reports(guardian:, year:)+ key = "rewind:#{guardian.user.username}:#{year}"+ reports = Discourse.redis.get(key)+ return nil unless reports++ MultiJson.load(reports, symbolize_keys: true)+ end++ def fetch_report(all_reports:, params:)+ all_reports[params.index]+ end+ end+enddiff --git a/plugins/discourse-rewind/app/services/discourse_rewind/fetch_reports.rb b/plugins/discourse-rewind/app/services/discourse_rewind/fetch_reports.rbindex 78dd8a943ce..bb4b6585b33 100644--- a/plugins/discourse-rewind/app/services/discourse_rewind/fetch_reports.rb+++ b/plugins/discourse-rewind/app/services/discourse_rewind/fetch_reports.rb@@ -20,6 +20,7 @@ module DiscourseRewind# @return [Service::Base::Context]CACHE_DURATION = Rails.env.development? ? 10.seconds : 3.days+ INITIAL_REPORT_COUNT = 3# The order here controls the order of reports in the UI,# so be careful when moving these around.@@ -45,7 +46,9 @@ module DiscourseRewindmodel :yearmodel :date+ model :all_reportsmodel :reports+ model :total_availableprivate@@ -74,13 +77,17 @@ module DiscourseRewindDate.new(year).all_yearend- def fetch_reports(date:, guardian:, year:)- key = "rewind:#{guardian.user.username}:#{year}"+ def fetch_all_reports(date:, guardian:, year:)+ key = cache_key(guardian.user.username, year)reports = Discourse.redis.get(key)if !reportsreports =- REPORTS.map { |report| report.call(date:, user: guardian.user, guardian:) }.compact+ REPORTS.filter_map do |report|+ report.call(date:, user: guardian.user, guardian:)+ rescue StandardError+ nil+ endDiscourse.redis.setex(key, CACHE_DURATION, MultiJson.dump(reports))elsereports = MultiJson.load(reports, symbolize_keys: true)@@ -88,5 +95,17 @@ module DiscourseRewindreportsend++ def fetch_reports(all_reports:)+ all_reports.first(INITIAL_REPORT_COUNT)+ end++ def fetch_total_available(all_reports:)+ all_reports.size+ end++ def cache_key(username, year)+ "rewind:#{username}:#{year}"+ endendenddiff --git a/plugins/discourse-rewind/assets/javascripts/discourse/components/rewind.gjs b/plugins/discourse-rewind/assets/javascripts/discourse/components/rewind.gjsindex e27b6b845b0..e3c781db035 100644--- a/plugins/discourse-rewind/assets/javascripts/discourse/components/rewind.gjs+++ b/plugins/discourse-rewind/assets/javascripts/discourse/components/rewind.gjs@@ -3,6 +3,7 @@ import { tracked } from "@glimmer/tracking";import { on } from "@ember/modifier";import { action } from "@ember/object";import didInsert from "@ember/render-modifiers/modifiers/did-insert";+import willDestroy from "@ember/render-modifiers/modifiers/will-destroy";import DButton from "discourse/components/d-button";import concatClass from "discourse/helpers/concat-class";import { ajax } from "discourse/lib/ajax";@@ -27,26 +28,103 @@ import TimeOfDayActivity from "discourse/plugins/discourse-rewind/discourse/compimport TopWords from "discourse/plugins/discourse-rewind/discourse/components/reports/top-words";import WritingAnalysis from "discourse/plugins/discourse-rewind/discourse/components/reports/writing-analysis";+const BUFFER_SIZE = 3;+const SCROLL_THRESHOLD = 0.7;+export default class Rewind extends Component {@tracked rewind = [];@tracked fullScreen = true;@tracked loadingRewind = false;+ @tracked totalAvailable = 0;+ @tracked isLoadingMore = false;+ nextReportIndex = 0;@actionregisterScrollWrapper(element) {this.scrollWrapper = element;+ this.scrollWrapper.addEventListener("scroll", this.handleScroll);+ }++ @action+ cleanup() {+ this.scrollWrapper?.removeEventListener("scroll", this.handleScroll);}@actionasync loadRewind() {try {this.loadingRewind = true;- this.rewind = await ajax("/rewinds");+ const response = await ajax("/rewinds.json");+ this.rewind = response.reports;+ this.totalAvailable = response.total_available;+ this.nextReportIndex = response.reports.length;} catch (e) {popupAjaxError(e);} finally {this.loadingRewind = false;}++ // Load more if content fits on screen without scrolling+ this.checkIfMoreContentNeeded();+ }++ checkIfMoreContentNeeded() {+ if (!this.scrollWrapper || this.nextReportIndex >= this.totalAvailable) {+ return;+ }++ const { scrollHeight, clientHeight } = this.scrollWrapper;+ if (scrollHeight <= clientHeight) {+ this.preloadNextReports();+ }+ }++ @action+ handleScroll() {+ if (this.isLoadingMore || this.nextReportIndex >= this.totalAvailable) {+ return;+ }++ const { scrollTop, scrollHeight, clientHeight } = this.scrollWrapper;+ const scrollProgress = (scrollTop + clientHeight) / scrollHeight;++ if (scrollProgress > SCROLL_THRESHOLD) {+ this.preloadNextReports();+ }+ }++ async preloadNextReports() {+ if (this.nextReportIndex >= this.totalAvailable) {+ return;+ }++ const targetIndex = Math.min(+ this.nextReportIndex + BUFFER_SIZE,+ this.totalAvailable+ );++ this.isLoadingMore = true;++ try {+ while (this.nextReportIndex < targetIndex) {+ try {+ const response = await ajax(`/rewinds/${this.nextReportIndex}.json`, {+ ignoreUnsent: false,+ });+ if (response.report) {+ this.rewind = [...this.rewind, response.report];+ }+ } catch {+ // Skip failed reports and continue loading+ }+ this.nextReportIndex++;+ }+ } finally {+ this.isLoadingMore = false;+ }++ // Re-check in case we need more content (failed reports or content fits on screen)+ this.checkIfMoreContentNeeded();}@action@@ -144,6 +222,7 @@ export default class Rewind extends Component {<divclass="rewind__scroll-wrapper"{{didInsert this.registerScrollWrapper}}+ {{willDestroy this.cleanup}}>{{#each this.rewind as |report|}}@@ -158,6 +237,12 @@ export default class Rewind extends Component {{{/if}}{{/let}}{{/each}}++ {{#if this.isLoadingMore}}+ <div class="rewind-loader --more">+ <div class="spinner small"></div>+ </div>+ {{/if}}</div>{{#if this.showPrev}}diff --git a/plugins/discourse-rewind/config/locales/server.en.yml b/plugins/discourse-rewind/config/locales/server.en.ymlindex 64c4787967d..1294cd525a1 100644--- a/plugins/discourse-rewind/config/locales/server.en.yml+++ b/plugins/discourse-rewind/config/locales/server.en.yml@@ -4,3 +4,5 @@ en:discourse_rewind:report_failed: "Failed to generate Discourse Rewind report."invalid_year: "Rewind can only be generated in January or December."+ reports_not_cached: "Reports have not been generated yet. Please refresh the page."+ report_not_found: "Report not found."diff --git a/plugins/discourse-rewind/config/routes.rb b/plugins/discourse-rewind/config/routes.rbindex 5ee0cbe864c..0055bda9326 100644--- a/plugins/discourse-rewind/config/routes.rb+++ b/plugins/discourse-rewind/config/routes.rb@@ -1,5 +1,8 @@# frozen_string_literal: true-DiscourseRewind::Engine.routes.draw { get "/rewinds" => "rewinds#show" }+DiscourseRewind::Engine.routes.draw do+ get "/rewinds" => "rewinds#index"+ get "/rewinds/:index" => "rewinds#show"+endDiscourse::Application.routes.draw { mount ::DiscourseRewind::Engine, at: "/" }diff --git a/plugins/discourse-rewind/spec/requests/rewinds_controller_spec.rb b/plugins/discourse-rewind/spec/requests/rewinds_controller_spec.rbindex cac8caf4a3d..ef60e92d9bf 100644--- a/plugins/discourse-rewind/spec/requests/rewinds_controller_spec.rb+++ b/plugins/discourse-rewind/spec/requests/rewinds_controller_spec.rb@@ -3,7 +3,7 @@RSpec.describe DiscourseRewind::RewindsController dobefore { SiteSetting.discourse_rewind_enabled = true }- describe "#show" do+ describe "#index" dofab!(:current_user, :user)before { sign_in(current_user) }@@ -22,23 +22,82 @@ RSpec.describe DiscourseRewind::RewindsController docontext "when in valid month" dobefore { freeze_time DateTime.parse("2022-12-24") }- it "returns 200" do+ it "returns 200 with reports and total_available" doget "/rewinds.json"expect(response.status).to eq(200)+ body = response.parsed_body+ expect(body).to have_key("reports")+ expect(body).to have_key("total_available")+ expect(body["reports"].size).to be <= DiscourseRewind::FetchReports::INITIAL_REPORT_COUNT+ expect(body["total_available"]).to be >= body["reports"].sizeend- context "when reports are not found or error" do+ context "when some reports fail" dobefore doDiscourseRewind::Action::TopWords.stubs(:call).raises(StandardError.new("Some error"))end- it "returns 404 with message" do+ it "returns reports excluding the failed ones" doget "/rewinds.json"+ expect(response.status).to eq(200)+ body = response.parsed_body+ expect(body["reports"]).to be_an(Array)+ expect(body["reports"].map { |r| r["identifier"] }).not_to include("top-words")+ end+ end+ end+ end++ describe "#show" do+ fab!(:current_user, :user)++ before { sign_in(current_user) }++ context "when out of valid month" do+ before { freeze_time DateTime.parse("2022-11-24") }++ it "returns 404" do+ get "/rewinds/0.json"++ expect(response.status).to eq(404)+ expect(response.parsed_body["errors"].first).to eq(I18n.t("discourse_rewind.invalid_year"))+ end+ end++ context "when in valid month" do+ before { freeze_time DateTime.parse("2022-12-24") }++ context "when reports are not cached" do+ it "returns 404 with message" do+ get "/rewinds/0.json"++ expect(response.status).to eq(404)+ expect(response.parsed_body["errors"].first).to eq(+ I18n.t("discourse_rewind.reports_not_cached"),+ )+ end+ end++ context "when reports are cached" do+ before { get "/rewinds.json" }++ it "returns 200 with the requested report" do+ get "/rewinds/0.json"++ expect(response.status).to eq(200)+ body = response.parsed_body+ expect(body).to have_key("report")+ expect(body["report"]).to have_key("identifier")+ end++ it "returns 404 for invalid index" do+ get "/rewinds/999.json"+expect(response.status).to eq(404)expect(response.parsed_body["errors"].first).to eq(- I18n.t("discourse_rewind.report_failed"),+ I18n.t("discourse_rewind.report_not_found"),)endend