From 6231f01860efe7418dfd5ff6fab8d5d1067c1b0f Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 12 Nov 2026 23:07:35 -0500 Subject: [PATCH] fix: Forced fetches dropped or stale while another fetch is in flight (#14573) * fix: Run forced document tree fetches that arrive while a fetch is in flight * fix: Run forced store fetches that arrive while a fetch is in flight * test --- app/models/Collection.ts | 13 +-- app/models/base/CoalescedFetch.test.ts | 110 +++++++++++++++++++++++++ app/models/base/CoalescedFetch.ts | 76 +++++++++++++++++ app/models/base/Model.ts | 53 +++++------- app/models/base/NavigableModel.ts | 14 +--- app/stores/RevisionsStore.ts | 14 +--- app/stores/base/Store.ts | 56 +++++++------ 7 files changed, 245 insertions(+), 91 deletions(-) create mode 100644 app/models/base/CoalescedFetch.test.ts create mode 100644 app/models/base/CoalescedFetch.ts diff --git a/app/models/Collection.ts b/app/models/Collection.ts index 792ba38d57..837ed8ff74 100644 --- a/app/models/Collection.ts +++ b/app/models/Collection.ts @@ -18,6 +18,7 @@ import { import { sortNavigationNodes } from "@shared/utils/collections"; import type CollectionsStore from "~/stores/CollectionsStore"; import type Document from "~/models/Document"; +import { CoalescedFetch } from "~/models/base/CoalescedFetch"; import ParanoidModel from "~/models/base/ParanoidModel"; import { client } from "~/utils/ApiClient"; import type User from "./User"; @@ -266,15 +267,11 @@ export default class Collection extends ParanoidModel { } fetchDocuments = async (options?: { force: boolean }) => { - if (this.isFetching) { - return; - } if (this.documents && options?.force !== true) { return; } - try { - this.isFetching = true; + await this.documentsFetch.run(async () => { const res = await client.post("/collections.documents", { id: this.id, }); @@ -283,9 +280,7 @@ export default class Collection extends ParanoidModel { runInAction(() => { this.documents = res.data; }); - } finally { - this.isFetching = false; - } + }, options?.force); }; /** @@ -494,5 +489,5 @@ export default class Collection extends ParanoidModel { } } - private isFetching = false; + private documentsFetch = new CoalescedFetch(); } diff --git a/app/models/base/CoalescedFetch.test.ts b/app/models/base/CoalescedFetch.test.ts new file mode 100644 index 0000000000..8773c82219 --- /dev/null +++ b/app/models/base/CoalescedFetch.test.ts @@ -0,0 +1,110 @@ +import { CoalescedFetch, KeyedCoalescedFetch } from "./CoalescedFetch"; + +function deferred() { + let resolve = () => {}; + let reject = (_err: Error) => {}; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} + +describe("CoalescedFetch", () => { + it("should share an in-flight request with unforced calls", async () => { + const queue = new CoalescedFetch(); + const request = deferred(); + const fetch = vi.fn(() => request.promise); + + const first = queue.run(fetch); + const second = queue.run(fetch); + request.resolve(); + await Promise.all([first, second]); + + expect(fetch).toHaveBeenCalledTimes(1); + }); + + it("should run one more request after an in-flight request when forced", async () => { + const queue = new CoalescedFetch(); + const requests = [deferred(), deferred()]; + let calls = 0; + const fetch = vi.fn(() => requests[calls++].promise); + + const first = queue.run(fetch); + const forced = queue.run(fetch, true); + const forcedAgain = queue.run(fetch, true); + expect(fetch).toHaveBeenCalledTimes(1); + + requests[0].resolve(); + await first; + await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(2)); + + let settled = false; + void forced.then(() => { + settled = true; + }); + await Promise.resolve(); + expect(settled).toBe(false); + + requests[1].resolve(); + await Promise.all([forced, forcedAgain]); + expect(fetch).toHaveBeenCalledTimes(2); + }); + + it("should run the forced request when the in-flight request fails", async () => { + const queue = new CoalescedFetch(); + const failed = deferred(); + const fetch = vi + .fn<() => Promise>() + .mockReturnValueOnce(failed.promise) + .mockResolvedValueOnce(undefined); + + const first = queue.run(fetch); + const forced = queue.run(fetch, true); + failed.reject(new Error("Network error")); + + await expect(first).rejects.toThrow("Network error"); + await expect(forced).resolves.toBeUndefined(); + expect(fetch).toHaveBeenCalledTimes(2); + }); + + it("should start a new request after the previous one completes", async () => { + const queue = new CoalescedFetch(); + const fetch = vi.fn(() => Promise.resolve()); + + await queue.run(fetch); + await queue.run(fetch); + + expect(fetch).toHaveBeenCalledTimes(2); + }); +}); + +describe("KeyedCoalescedFetch", () => { + it("should share requests for the same key only", async () => { + const fetches = new KeyedCoalescedFetch(); + const fetch = vi.fn((value: string) => Promise.resolve(value)); + + const results = await Promise.all([ + fetches.run("a", () => fetch("a1")), + fetches.run("a", () => fetch("a2")), + fetches.run("b", () => fetch("b1")), + ]); + + expect(results).toEqual(["a1", "a1", "b1"]); + expect(fetch).toHaveBeenCalledTimes(2); + }); + + it("should return the result of the follow-up request to a forced call", async () => { + const fetches = new KeyedCoalescedFetch(); + let calls = 0; + const fetch = () => Promise.resolve(++calls); + + const results = await Promise.all([ + fetches.run("a", fetch), + fetches.run("a", fetch, true), + ]); + + expect(results).toEqual([1, 2]); + expect(await fetches.run("a", fetch)).toBe(3); + }); +}); diff --git a/app/models/base/CoalescedFetch.ts b/app/models/base/CoalescedFetch.ts new file mode 100644 index 0000000000..16f983ed54 --- /dev/null +++ b/app/models/base/CoalescedFetch.ts @@ -0,0 +1,76 @@ +/** + * Runs an async fetch so that concurrent calls share one request. A forced + * call made while a request is in flight runs one more request after it, so + * the result is never older than the forced call. + */ +export class CoalescedFetch { + /** Whether no request is in flight or queued. */ + get isIdle(): boolean { + return !this.current && !this.next; + } + + /** + * Runs the fetch, or joins the request that is in flight. + * + * @param fetch the function that performs the request. + * @param force whether the result must start after this call. + * @returns a promise that resolves with the result of the request. + */ + run(fetch: () => Promise, force = false): Promise { + if (!this.current) { + this.current = fetch().finally(() => { + this.current = undefined; + }); + return this.current; + } + + if (!force) { + return this.current; + } + + this.next ??= this.current + .catch(() => undefined) + .then(() => { + this.next = undefined; + return this.run(fetch, true); + }); + return this.next; + } + + private current?: Promise; + private next?: Promise; +} + +/** + * Runs a separate {@link CoalescedFetch} for each key, and discards it when + * its requests are complete. + */ +export class KeyedCoalescedFetch { + /** + * Runs the fetch for the key, or joins the request for the key that is in + * flight. + * + * @param key the key that identifies the resource. + * @param fetch the function that performs the request. + * @param force whether the result must start after this call. + * @returns a promise that resolves with the result of the request. + */ + run(key: string, fetch: () => Promise, force = false): Promise { + let entry = this.entries.get(key); + if (!entry) { + entry = new CoalescedFetch(); + this.entries.set(key, entry); + } + + const promise = entry.run(fetch, force); + const cleanup = () => { + if (entry.isIdle && this.entries.get(key) === entry) { + this.entries.delete(key); + } + }; + void promise.then(cleanup, cleanup); + return promise; + } + + private entries = new Map>(); +} diff --git a/app/models/base/Model.ts b/app/models/base/Model.ts index 53f5e4febb..d5201203a8 100644 --- a/app/models/base/Model.ts +++ b/app/models/base/Model.ts @@ -128,42 +128,34 @@ export default abstract class Model { this: Model, options: { withoutPolicies?: boolean } = {} ): Promise { - // this is to ensure that multiple loads don’t happen in parallel - if (this.loadingRelations) { - return this.loadingRelations; - } + return this.store.relationFetches.run(this.id, () => { + const promises = []; - const promises = []; + const relations = getRelationsForModelClass( + this.constructor as typeof Model + ); - const relations = getRelationsForModelClass( - this.constructor as typeof Model - ); - - if (relations) { - for (const properties of relations.values()) { - const store = this.store.rootStore.getStoreForModelName( - properties.relationClassResolver().modelName - ); - if ("canFetchById" in store && store.canFetchById) { - const id = this[properties.idKey]; - if (id) { - promises.push(store.fetch(id as string)); + if (relations) { + for (const properties of relations.values()) { + const store = this.store.rootStore.getStoreForModelName( + properties.relationClassResolver().modelName + ); + if ("canFetchById" in store && store.canFetchById) { + const id = this[properties.idKey]; + if (id) { + promises.push(store.fetch(id as string)); + } } } } - } - const policy = this.store.rootStore.policies.get(this.id); - if (!policy && !options.withoutPolicies && this.store.canFetchById) { - promises.push(this.store.fetch(this.id, { force: true })); - } + const policy = this.store.rootStore.policies.get(this.id); + if (!policy && !options.withoutPolicies && this.store.canFetchById) { + promises.push(this.store.fetch(this.id, { force: true })); + } - try { - this.loadingRelations = Promise.all(promises); - return await this.loadingRelations; - } finally { - this.loadingRelations = undefined; - } + return Promise.all(promises); + }); } /** @@ -348,9 +340,6 @@ export default abstract class Model { protected persistedAttributes: Partial = {}; - /** A promise that resolves when all relations have been loaded. */ - private loadingRelations: Promise | undefined; - /** A boolean representing if the constructor has been called. */ private initialized = false; } diff --git a/app/models/base/NavigableModel.ts b/app/models/base/NavigableModel.ts index 06d4525408..34c7068643 100644 --- a/app/models/base/NavigableModel.ts +++ b/app/models/base/NavigableModel.ts @@ -1,6 +1,7 @@ import { action, computed, observable, runInAction } from "mobx"; import type { JSONObject, NavigationNode } from "@shared/types"; import { client } from "~/utils/ApiClient"; +import { CoalescedFetch } from "./CoalescedFetch"; import Model from "./Model"; import type Document from "../Document"; import type DocumentsStore from "~/stores/DocumentsStore"; @@ -59,7 +60,7 @@ export default abstract class NavigableModel extends Model { }); } - private isFetching = false; + private documentsFetch = new CoalescedFetch(); /** The document ID associated with this model. */ documentId?: string; @@ -74,24 +75,17 @@ export default abstract class NavigableModel extends Model { params: JSONObject; force?: boolean; }) { - if (this.isFetching) { - return; - } - if (this.documents && options.force !== true) { return; } - try { - this.isFetching = true; + await this.documentsFetch.run(async () => { const res = await client.post(options.path, options.params); runInAction(() => { this.node = res.data; }); - } finally { - this.isFetching = false; - } + }, options.force); } /** diff --git a/app/stores/RevisionsStore.ts b/app/stores/RevisionsStore.ts index 9073956727..16a4747aca 100644 --- a/app/stores/RevisionsStore.ts +++ b/app/stores/RevisionsStore.ts @@ -47,19 +47,7 @@ export default class RevisionsStore extends Store { */ fetchLatest = async (documentId: string): Promise => { const id = RevisionHelper.latestId(documentId); - const inflight = this.requests.get(id); - if (inflight) { - return inflight; - } - - const promise = this.requestLatest(documentId); - this.requests.set(id, promise); - - try { - return await promise; - } finally { - this.requests.delete(id); - } + return this.fetches.run(id, () => this.requestLatest(documentId)); }; private async requestLatest(documentId: string): Promise { diff --git a/app/stores/base/Store.ts b/app/stores/base/Store.ts index 5dc46734b2..71774c5e3d 100644 --- a/app/stores/base/Store.ts +++ b/app/stores/base/Store.ts @@ -22,6 +22,7 @@ import { type JSONObject } from "@shared/types"; import type RootStore from "~/stores/RootStore"; import type Policy from "~/models/Policy"; import type ArchivableModel from "~/models/base/ArchivableModel"; +import { KeyedCoalescedFetch } from "~/models/base/CoalescedFetch"; import type Model from "~/models/base/Model"; import { LifecycleManager } from "~/models/decorators/Lifecycle"; import { getInverseRelationsForModelClass } from "~/models/decorators/Relation"; @@ -89,8 +90,8 @@ export default abstract class Store { @observable isLoaded = false; - // oxlint-disable-next-line no-explicit-any - requests: Map> = new Map(); + /** Calls to `Model.loadRelations` that are in flight, keyed by model id. */ + relationFetches = new KeyedCoalescedFetch(); model: ModelClass; @@ -488,25 +489,24 @@ export default abstract class Store { return item; } - if (this.requests.has(id)) { - return this.requests.get(id); - } + return this.fetches.run( + id, + async () => { + runInAction(() => { + this.isFetching = true; + }); - this.isFetching = true; + try { + const res = await client.post(`/${this.apiEndpoint}.info`, { + id, + }); - const promise = new Promise((resolve, reject) => { - client - .post(`/${this.apiEndpoint}.info`, { - id, - }) - .then((res) => - runInAction(() => { + return runInAction(() => { invariant(res?.data, "Data should be available"); this.addPolicies(res.policies); - resolve(this.add(accessor(res))); - }) - ) - .catch((err) => { + return this.add(accessor(res)); + }); + } catch (err) { if ( err instanceof AuthorizationError || err instanceof NotFoundError @@ -514,16 +514,15 @@ export default abstract class Store { this.remove(id); } - reject(err); - }) - .finally(() => { - this.requests.delete(id); - this.isFetching = false; - }); - }); - - this.requests.set(id, promise); - return promise; + throw err; + } finally { + runInAction(() => { + this.isFetching = false; + }); + } + }, + Boolean(options.force) + ); } // Not annotated: subclasses replace this field, and MobX makes an annotated @@ -686,6 +685,9 @@ export default abstract class Store { } } + /** Requests by `fetch` that are in flight, keyed by model id. */ + protected fetches = new KeyedCoalescedFetch(); + /** Results of `fetchAll` calls keyed by their params, see `fetchAllIfNeeded`. */ private fetchAllResults = new Map>(); }