A platform for community discussion. Free, open, simple.
FIX: Correct the debounced evaluation path in `DAsyncContent` (#42387)
Sérgio Saquetim16844073fc28
diff --git a/frontend/discourse/app/ui-kit/d-async-content.gts b/frontend/discourse/app/ui-kit/d-async-content.gtsindex 867bd455de4..3c9ce7e80b1 100644--- a/frontend/discourse/app/ui-kit/d-async-content.gts+++ b/frontend/discourse/app/ui-kit/d-async-content.gts@@ -1,6 +1,7 @@import Component from "@glimmer/component";import { cached } from "@glimmer/tracking";import { hash } from "@ember/helper";+import { cancel } from "@ember/runloop";import { type TrustedHTML, trustHTML } from "@ember/template";import type { WithBoundArgs } from "@glint/template";import { TrackedAsyncData } from "ember-async-data";@@ -58,6 +59,16 @@ interface DAsyncContentSignature<T> {* Whether to debounce re-invocations of the function form of `@asyncData`,* so rapidly changing input does not refetch on every change. `true` uses* the default input delay; a number sets the delay in milliseconds.+ *+ * The first evaluation is never debounced: there is no rapid input to+ * coalesce yet, and delaying it would only postpone the initial paint. The+ * delay applies from the second evaluation onward.+ *+ * A debounced re-invocation runs from a timer, outside the computation that+ * produces the data, so state the function reads there is *not* autotracked+ * and changing it will not reload. Only an un-debounced evaluation tracks+ * such reads, so a source that is ever debounced must never rely on+ * autotracking: pass every reactive dependency it has through `@context`.*/debounce?: boolean | number;@@ -110,9 +121,13 @@ interface DAsyncContentSignature<T> {export default class DAsyncContent<T> extends Component<DAsyncContentSignature<T>> {- #debounce: boolean | number | undefined = false;#abortController: AbortController | null = null;+ // Whether the function form of `@asyncData` has been evaluated at least once, so the+ // first evaluation can skip debouncing: there is no rapid input to coalesce yet, and a+ // delay there would only postpone the initial paint.+ #hasEvaluated = false;+// The value from the most recent resolution, kept so we can keep rendering it// while a *subsequent* load is pending (opt-in via `@retainWhileReloading`).// Plain fields, not tracked: they are written from within the `resolution`@@ -121,9 +136,16 @@ export default class DAsyncContent<T> extends Component<#lastResolvedValue: T | undefined = undefined;#hasResolvedOnce = false;+ // The scheduled debounced invocation and the settle functions of the promise standing+ // in for it, kept so a superseded or cancelled evaluation can still be settled.+ #debounceTimer: Parameters<typeof cancel>[0] = undefined;+ #pendingResolve: ((value: T | PromiseLike<T>) => void) | null = null;+ #pendingReject: ((reason?: unknown) => void) | null = null;+willDestroy(): void {super.willDestroy();this.#abortController?.abort();+ this.#cancelPendingDebounce();}/**@@ -188,6 +210,9 @@ export default class DAsyncContent<T> extends Component<}if (asyncData instanceof TrackedAsyncData) {+ // An externally-managed instance produces nothing for a superseded promise to+ // adopt, so the scheduled call is simply dropped and its promise settled.+ this.#cancelPendingDebounce();return asyncData;}@@ -198,25 +223,30 @@ export default class DAsyncContent<T> extends Component<let value: T | Promise<T> | Promise<void> | undefined;+ // This evaluation supersedes any call still waiting on its timer, whatever shape+ // `@asyncData` now has, so drop that call and keep hold of the promise standing in+ // for it. That promise then adopts this evaluation's outcome: cancelling its timer+ // removed the only thing that would have settled it, and the `TrackedAsyncData`+ // built on it would otherwise stay pending for good.+ const superseded = this.#takePendingDebounce();+if (this.#isPromise(asyncData)) {value = asyncData;} else if (typeof asyncData === "function") {- value = this.#debounce- ? new Promise<T>((resolve, reject) => {- discourseDebounce(- this,- this.#resolveAsyncData,- asyncData,- context,- signal,- resolve,- reject,- this.#debounce- );- })+ const debounceDelay = this.#debounceDelay;++ value = debounceDelay+ ? this.#scheduleDebounced(asyncData, context, signal, debounceDelay): this.#resolveAsyncData(asyncData, context, signal);++ // Untracked, like the retained-value fields above: it only gates the *next*+ // evaluation, so it never needs to drive its own invalidation.+ /* eslint-disable-next-line ember/no-side-effects */+ this.#hasEvaluated = true;}+ superseded?.(value as T | Promise<T>);+// A function may return a synchronous value (a client-only data source) rather// than a promise. `TrackedAsyncData` resolves a non-promise synchronously, so such// a source renders content with no pending/loading phase; a promise resolves@@ -232,6 +262,18 @@ export default class DAsyncContent<T> extends Component<return this.args.errorMode ?? DEFAULT_ERROR_MODE;}+ // Resolved at evaluation time rather than recorded as a side effect of the previous+ // resolve, so a changed `@debounce` reaches the very next evaluation instead of the+ // one after it.+ get #debounceDelay(): number | undefined {+ if (!this.#hasEvaluated) {+ return undefined;+ }++ const { debounce } = this.args;+ return debounce === true ? INPUT_DELAY : debounce || undefined;+ }+@bindverifyParameters({ hasErrorBlock }: { hasErrorBlock: boolean }) {if (hasErrorBlock && this.args.errorMode) {@@ -247,6 +289,73 @@ export default class DAsyncContent<T> extends Component<return value instanceof Promise || value instanceof RsvpPromise;}+ // Creates the promise standing in for a deferred call, then schedules that call.+ #scheduleDebounced(+ asyncData: AsyncDataFn<T>,+ context: unknown,+ signal: AbortSignal,+ delay: number+ ): Promise<T> {+ let resolve!: (value: T | PromiseLike<T>) => void;+ let reject!: (reason?: unknown) => void;++ const promise = new Promise<T>((resolveFn, rejectFn) => {+ resolve = resolveFn;+ reject = rejectFn;+ });++ this.#pendingResolve = resolve;+ this.#pendingReject = reject;+ this.#debounceTimer = discourseDebounce(+ this,+ this.#resolveAsyncData,+ asyncData,+ context,+ signal,+ resolve,+ reject,+ delay+ );++ return promise;+ }++ // Drops a call still waiting on its timer and hands back the `resolve` of the promise+ // standing in for it, so the caller can settle that promise with whatever supersedes+ // it. Returns `undefined` when no call is scheduled.+ #takePendingDebounce(): ((value: T | PromiseLike<T>) => void) | undefined {+ if (this.#debounceTimer == null) {+ return undefined;+ }++ cancel(this.#debounceTimer);+ this.#debounceTimer = undefined;++ const resolve = this.#pendingResolve ?? undefined;+ this.#pendingResolve = null;+ this.#pendingReject = null;++ return resolve;+ }++ // Drops a scheduled call when nothing is left to hand its promise, and rejects that+ // promise: nothing remains to settle it once its timer is cancelled, and the+ // `TrackedAsyncData` built on it would stay pending for good. The rejection is never+ // rendered, since the instance it backs is no longer the one `data` returns.+ #cancelPendingDebounce(): void {+ if (this.#debounceTimer == null) {+ return;+ }++ const reject = this.#pendingReject;+ cancel(this.#debounceTimer);+ this.#debounceTimer = undefined;+ this.#pendingResolve = null;+ this.#pendingReject = null;++ reject?.(new Error("The load was cancelled before it ran"));+ }+// Aborts the previous fetch's controller and mints a fresh one, returning its// signal. Kept out of the `data` getter body so the (benign, untracked) mutation// isn't a computed side-effect.@@ -264,21 +373,31 @@ export default class DAsyncContent<T> extends Component<resolve?: (value: T | PromiseLike<T>) => void,reject?: (reason?: unknown) => void): T | Promise<T> | Promise<void> {- this.#debounce =- this.args.debounce === true ? INPUT_DELAY : this.args.debounce;-// The async function receives an AbortSignal as a second arg so it can cancel an// in-flight request when superseded; existing zero/one-arg functions ignore it.- // When a resolve fn is provided (the debounced path) we settle the outer promise;- // otherwise we return the function's result directly (a promise OR a sync value).- //- // The debounced path only runs against async data sources, so the result is- // cast to `Promise<T>` to settle the outer promise via `.then`/`.catch`.- return resolve- ? (asyncData(context, { signal }) as Promise<T>)- .then(resolve)- .catch(reject)- : asyncData(context, { signal });+ if (!resolve) {+ // The un-debounced path returns the function's result directly (a promise OR a+ // sync value), so a synchronous source still resolves with no pending phase.+ // A synchronous throw is turned into a rejection because it would otherwise+ // propagate out of the `data` getter and break the render instead of reaching+ // the error block. This path also serves the first evaluation of a debounced+ // source, which is never debounced.+ try {+ return asyncData(context, { signal });+ } catch (error) {+ return Promise.reject<T>(error);+ }+ }++ // The debounced path settles the outer promise that stands in for the deferred+ // call. It may run against a synchronous source, so the result can be a plain+ // value rather than a promise. Calling the source *inside* the executor both+ // assimilates either shape and converts a synchronous throw into a rejection —+ // `Promise.resolve(fn())` evaluates `fn()` first, so a throw there escapes the+ // debounce timer and leaves the outer promise unsettled forever.+ return new Promise<T>((settle) => settle(asyncData(context, { signal })))+ .then(resolve)+ .catch(reject);}<template>diff --git a/frontend/discourse/tests/integration/ui-kit/d-async-content-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-async-content-test.gjsindex ff6a22b455b..f4fe9aed3b0 100644--- a/frontend/discourse/tests/integration/ui-kit/d-async-content-test.gjs+++ b/frontend/discourse/tests/integration/ui-kit/d-async-content-test.gjs@@ -2,7 +2,7 @@ import Component from "@glimmer/component";import { tracked } from "@glimmer/tracking";import { on } from "@ember/modifier";import { action } from "@ember/object";-import { click, render, settled, waitFor } from "@ember/test-helpers";+import { click, render, rerender, settled, waitFor } from "@ember/test-helpers";import { TrackedAsyncData } from "ember-async-data";import { module, test } from "qunit";import { Promise as RsvpPromise } from "rsvp";@@ -96,6 +96,32 @@ module("Integration | ui-kit | DAsyncContent", function (hooks) {assert.dom(".content").hasText("data");});++ test("it surfaces a synchronous throw", async function (assert) {+ const load = () => {+ throw new Error("sync failure");+ };++ await render(+ <template>+ <DAsyncContent @asyncData={{load}}>+ <:content as |data|>+ <div class="content">{{data}}</div>+ </:content>+ <:error as |error|>+ <div class="error">{{error.message}}</div>+ </:error>+ </DAsyncContent>+ </template>+ );++ assert+ .dom(".error")+ .hasText(+ "sync failure",+ "a throw becomes a rejection instead of escaping the getter and breaking the render"+ );+ });});module("@context", function () {@@ -151,6 +177,611 @@ module("Integration | ui-kit | DAsyncContent", function (hooks) {});});+ // Drives the debounced tests from outside a component, so state can be changed+ // without `click` awaiting the debounce timer in between.+ class DebounceState {+ @tracked context = "first";+ @tracked rendered = true;+ @tracked debounce = true;+ @tracked source = null;+ }++ module("@debounce", function () {+ // The debounced path only engages from the second evaluation onward, so this asserts+ // after a context change rather than on first render.+ test("it accepts a synchronous source", async function (assert) {+ await render(+ class extends Component {+ @tracked context = "first";++ load = (context) => context;++ @action+ changeContext() {+ this.context = "second";+ }++ <template>+ <button {{on "click" this.changeContext}}>Change Context</button>+ <DAsyncContent+ @asyncData={{this.load}}+ @context={{this.context}}+ @debounce={{true}}+ >+ <:content as |data|>+ <div class="content">{{data}}</div>+ </:content>+ </DAsyncContent>+ </template>+ }+ );++ assert.dom(".content").hasText("first");++ await click("button");++ assert+ .dom(".content")+ .hasText("second", "a plain value settles the debounced promise");+ });++ test("it surfaces a synchronous throw", async function (assert) {+ await render(+ class extends Component {+ @tracked context = "first";++ load = (context) => {+ if (context === "second") {+ throw new Error("sync failure");+ }++ return context;+ };++ @action+ changeContext() {+ this.context = "second";+ }++ <template>+ <button {{on "click" this.changeContext}}>Change Context</button>+ <DAsyncContent+ @asyncData={{this.load}}+ @context={{this.context}}+ @debounce={{true}}+ >+ <:content as |data|>+ <div class="content">{{data}}</div>+ </:content>+ <:error as |error|>+ <div class="error">{{error.message}}</div>+ </:error>+ </DAsyncContent>+ </template>+ }+ );++ assert.dom(".content").hasText("first");++ await click("button");++ assert+ .dom(".error")+ .hasText(+ "sync failure",+ "a throw rejects the debounced promise instead of escaping it unsettled"+ );+ });++ test("it does not retain stale content after a synchronous throw", async function (assert) {+ await render(+ class extends Component {+ @tracked context = "first";++ load = (context) => {+ if (context === "second") {+ throw new Error("sync failure");+ }++ return context;+ };++ @action+ changeContext() {+ this.context = "second";+ }++ <template>+ <button {{on "click" this.changeContext}}>Change Context</button>+ <DAsyncContent+ @asyncData={{this.load}}+ @context={{this.context}}+ @debounce={{true}}+ @retainWhileReloading={{true}}+ >+ <:content as |data|>+ <div class="content">{{data}}</div>+ </:content>+ <:error as |error|>+ <div class="error">{{error.message}}</div>+ </:error>+ </DAsyncContent>+ </template>+ }+ );++ assert.dom(".content").hasText("first");++ await click("button");++ assert.dom(".error").hasText("sync failure");+ assert+ .dom(".content")+ .doesNotExist(+ "a reload that never settles would leave the stale value on screen"+ );+ });++ test("it does not debounce the first evaluation", async function (assert) {+ const load = (context) => context;++ const renderPromise = render(+ <template>+ <div data-async-content-test>+ <DAsyncContent+ @asyncData={{load}}+ @context="first"+ @debounce={{true}}+ >+ <:content as |data|>+ <div class="content">{{data}}</div>+ </:content>+ </DAsyncContent>+ </div>+ </template>+ );++ // Asserting before the render settles, so the transient loading phase is+ // observable: a debounced first evaluation would delay the initial paint.+ await waitFor("[data-async-content-test]");++ assert.dom(".spinner").doesNotExist();+ assert+ .dom(".content")+ .hasText("first", "a sync source resolves without waiting out a delay");++ await renderPromise;+ });++ test("it honors a changed @debounce on the next evaluation", async function (assert) {+ await render(+ class extends Component {+ @tracked context = "first";+ @tracked debounce = false;++ // Both in one action, so a single evaluation sees the new `@debounce`+ // together with the new `@context`. Flipping `@debounce` on its own+ load = (context) => context;++ // would trigger an evaluation of its own that masks the defect.+ @action+ enableDebounceAndChangeContext() {+ this.debounce = true;+ this.context = "second";+ }++ <template>+ <button+ class="change"+ {{on "click" this.enableDebounceAndChangeContext}}+ >+ Change+ </button>+ <DAsyncContent+ @asyncData={{this.load}}+ @context={{this.context}}+ @debounce={{this.debounce}}+ >+ <:content as |data|>+ <div class="content">{{data}}</div>+ </:content>+ </DAsyncContent>+ </template>+ }+ );++ const changePromise = click(".change");++ // The debounced path wraps a sync source in a promise, so a pending phase+ // appears only if the new `@debounce` was read for this evaluation rather+ // than carried over from the previous one.+ await waitFor(".spinner");+ assert.dom(".spinner").exists();++ await changePromise;+ assert.dom(".content").hasText("second");+ });++ // The un-debounced path calls `@asyncData` inside the cached computation, so state it+ // reads is autotracked; the debounced path calls it from a timer, where it cannot be.+ // Consumers that debounce must therefore fold every reactive dependency into+ // `@context` instead of relying on the function to track it. These two pin that+ // asymmetry: without the un-debounced case the debounced assertion would also hold+ // for a source that simply never re-runs.+ test("an un-debounced source autotracks state read inside the function", async function (assert) {+ await render(+ class extends Component {+ @tracked suffix = "a";++ load = () => `value-${this.suffix}`;++ @action+ changeSuffix() {+ this.suffix = "b";+ }++ <template>+ <button {{on "click" this.changeSuffix}}>Suffix</button>+ <DAsyncContent @asyncData={{this.load}}>+ <:content as |data|>+ <div class="content">{{data}}</div>+ </:content>+ </DAsyncContent>+ </template>+ }+ );++ assert.dom(".content").hasText("value-a");++ await click("button");++ assert+ .dom(".content")+ .hasText("value-b", "the reload picks up the new value");+ });++ test("a debounced source does not autotrack state read inside the function", async function (assert) {+ await render(+ class extends Component {+ @tracked context = "first";+ @tracked suffix = "a";++ load = (context) => `${context}-${this.suffix}`;++ @action+ changeContext() {+ this.context = "second";+ }++ @action+ changeSuffix() {+ this.suffix = "b";+ }++ <template>+ <button+ class="context"+ {{on "click" this.changeContext}}+ >Context</button>+ <button+ class="suffix"+ {{on "click" this.changeSuffix}}+ >Suffix</button>+ <DAsyncContent+ @asyncData={{this.load}}+ @context={{this.context}}+ @debounce={{true}}+ >+ <:content as |data|>+ <div class="content">{{data}}</div>+ </:content>+ </DAsyncContent>+ </template>+ }+ );++ assert.dom(".content").hasText("first-a");++ // Engages the debounced path, which applies from the second evaluation onward.+ await click(".context");+ assert.dom(".content").hasText("second-a");++ await click(".suffix");++ assert+ .dom(".content")+ .hasText(+ "second-a",+ "a dependency read only inside the debounced call does not restart the load"+ );+ });++ // The first evaluation runs un-debounced, so it reaches the source through the+ // direct call rather than the promise executor. A throw there must still reject.+ test("it surfaces a synchronous throw on the first evaluation", async function (assert) {+ const load = () => {+ throw new Error("sync failure");+ };++ await render(+ <template>+ <DAsyncContent+ @asyncData={{load}}+ @context="first"+ @debounce={{true}}+ >+ <:content as |data|>+ <div class="content">{{data}}</div>+ </:content>+ <:error as |error|>+ <div class="error">{{error.message}}</div>+ </:error>+ </DAsyncContent>+ </template>+ );++ assert+ .dom(".error")+ .hasText(+ "sync failure",+ "the un-debounced first evaluation routes a throw to the error block too"+ );+ });++ test("it debounces an asynchronous source", async function (assert) {+ await render(+ class extends Component {+ @tracked context = "first";++ load = async (context) => context;++ @action+ changeContext() {+ this.context = "second";+ }++ <template>+ <button {{on "click" this.changeContext}}>Change Context</button>+ <DAsyncContent+ @asyncData={{this.load}}+ @context={{this.context}}+ @debounce={{true}}+ >+ <:content as |data|>+ <div class="content">{{data}}</div>+ </:content>+ </DAsyncContent>+ </template>+ }+ );++ assert.dom(".content").hasText("first");++ await click("button");++ assert+ .dom(".content")+ .hasText("second", "a promise source settles the debounced promise");+ });++ // `rerender` flushes the render without waiting out the debounce timer, so each+ // assignment below produces its own evaluation and they all land inside a single+ // window. `settled` then completes only if every superseded evaluation settled its+ // promise: an abandoned one would keep an async waiter pending and hang the test.+ test("it coalesces evaluations inside one window into a single call", async function (assert) {+ const seen = [];+ const state = new DebounceState();++ const load = (context) => {+ seen.push(context);+ return context;+ };++ await render(+ <template>+ <DAsyncContent+ @asyncData={{load}}+ @context={{state.context}}+ @debounce={{true}}+ >+ <:content as |data|>+ <div class="content">{{data}}</div>+ </:content>+ </DAsyncContent>+ </template>+ );++ assert.deepEqual(+ seen,+ ["first"],+ "the first evaluation runs immediately"+ );++ for (const next of ["a", "b", "c"]) {+ state.context = next;+ await rerender();+ }++ await settled();++ assert.deepEqual(+ seen,+ ["first", "c"],+ "the superseded evaluations never reach the source"+ );+ assert.dom(".content").hasText("c");+ });++ // Turning `@debounce` off makes the next evaluation take the direct path, which must+ // still drop the call the previous evaluation left waiting on its timer.+ test("it drops a scheduled call when the next evaluation is not debounced", async function (assert) {+ const seen = [];+ const state = new DebounceState();++ const load = (context) => {+ seen.push(context);+ return context;+ };++ await render(+ <template>+ <DAsyncContent+ @asyncData={{load}}+ @context={{state.context}}+ @debounce={{state.debounce}}+ >+ <:content as |data|>+ <div class="content">{{data}}</div>+ </:content>+ </DAsyncContent>+ </template>+ );++ assert.deepEqual(seen, ["first"]);++ // Schedules a debounced call for "second"...+ state.context = "second";+ await rerender();++ // ...which this evaluation supersedes before the timer fires.+ state.debounce = false;+ state.context = "third";+ await rerender();++ await settled();++ assert.deepEqual(+ seen,+ ["first", "third"],+ "the superseded call never reaches the source"+ );+ assert.dom(".content").hasText("third");+ });++ // Replacing `@asyncData` outright must drop a scheduled call just as a new context+ // does, for every shape the argument accepts.+ test("it drops a scheduled call when @asyncData is replaced by a promise", async function (assert) {+ const seen = [];+ const state = new DebounceState();+ state.source = (context) => {+ seen.push(context);+ return context;+ };++ await render(+ <template>+ <DAsyncContent+ @asyncData={{state.source}}+ @context={{state.context}}+ @debounce={{true}}+ >+ <:content as |data|>+ <div class="content">{{data}}</div>+ </:content>+ </DAsyncContent>+ </template>+ );++ assert.deepEqual(seen, ["first"]);++ state.context = "second";+ await rerender();++ state.source = Promise.resolve("replacement");+ await rerender();++ await settled();++ assert.deepEqual(+ seen,+ ["first"],+ "the superseded call never reaches the source"+ );+ assert.dom(".content").hasText("replacement");+ });++ test("it drops a scheduled call when @asyncData is replaced by a TrackedAsyncData", async function (assert) {+ const seen = [];+ const state = new DebounceState();+ state.source = (context) => {+ seen.push(context);+ return context;+ };++ await render(+ <template>+ <DAsyncContent+ @asyncData={{state.source}}+ @context={{state.context}}+ @debounce={{true}}+ >+ <:content as |data|>+ <div class="content">{{data}}</div>+ </:content>+ </DAsyncContent>+ </template>+ );++ assert.deepEqual(seen, ["first"]);++ state.context = "second";+ await rerender();++ state.source = new TrackedAsyncData(Promise.resolve("replacement"));+ await rerender();++ await settled();++ assert.deepEqual(+ seen,+ ["first"],+ "the superseded call never reaches the source"+ );+ assert.dom(".content").hasText("replacement");+ });++ test("it does not invoke a debounced source after the component is destroyed", async function (assert) {+ const seen = [];+ const state = new DebounceState();++ const load = (context) => {+ seen.push(context);+ return context;+ };++ await render(+ <template>+ {{#if state.rendered}}+ <DAsyncContent+ @asyncData={{load}}+ @context={{state.context}}+ @debounce={{true}}+ >+ <:content as |data|>+ <div class="content">{{data}}</div>+ </:content>+ </DAsyncContent>+ {{/if}}+ </template>+ );++ assert.deepEqual(seen, ["first"]);++ // Schedule a debounced load, then tear the component down before its timer fires.+ state.context = "second";+ await rerender();+ state.rendered = false;++ await settled();++ assert.deepEqual(+ seen,+ ["first"],+ "the scheduled load is cancelled rather than running against a dead component"+ );+ });+ });+module("<:loading>", function () {test("it displays the spinner when the block is not provided", async function (assert) {let resolvePromise;