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
This commit is contained in:
Tom Moor authored and GitHub committed 2026-11-12 23:07:35 -05:00
1 parent bcf282a2f6
commit 6231f01860
7 files changed
+245 -91

No files matched your search

+4 -9
View File
@@ -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();
}
+110
View File
@@ -0,0 +1,110 @@
import { CoalescedFetch, KeyedCoalescedFetch } from "./CoalescedFetch";
function deferred() {
let resolve = () => {};
let reject = (_err: Error) => {};
const promise = new Promise<void>((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<void>>()
.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<string>();
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<number>();
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);
});
});
+76
View File
@@ -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<T = void> {
/** 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<T>, force = false): Promise<T> {
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<T>;
private next?: Promise<T>;
}
/**
* Runs a separate {@link CoalescedFetch} for each key, and discards it when
* its requests are complete.
*/
export class KeyedCoalescedFetch<T> {
/**
* 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<T>, force = false): Promise<T> {
let entry = this.entries.get(key);
if (!entry) {
entry = new CoalescedFetch<T>();
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<string, CoalescedFetch<T>>();
}
+21 -32
View File
@@ -128,42 +128,34 @@ export default abstract class Model {
this: Model,
options: { withoutPolicies?: boolean } = {}
): Promise<unknown> {
// 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<Model> = {};
/** A promise that resolves when all relations have been loaded. */
private loadingRelations: Promise<unknown[]> | undefined;
/** A boolean representing if the constructor has been called. */
private initialized = false;
}
+4 -10
View File
@@ -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);
}
/**
+1 -13
View File
@@ -47,19 +47,7 @@ export default class RevisionsStore extends Store<Revision> {
*/
fetchLatest = async (documentId: string): Promise<Revision> => {
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<Revision> {
+29 -27
View File
@@ -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<T extends Model> {
@observable
isLoaded = false;
// oxlint-disable-next-line no-explicit-any
requests: Map<string, Promise<any>> = new Map();
/** Calls to `Model.loadRelations` that are in flight, keyed by model id. */
relationFetches = new KeyedCoalescedFetch<unknown>();
model: ModelClass<T>;
@@ -488,25 +489,24 @@ export default abstract class Store<T extends Model> {
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<T>((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<T extends Model> {
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<T extends Model> {
}
}
/** Requests by `fetch` that are in flight, keyed by model id. */
protected fetches = new KeyedCoalescedFetch<T>();
/** Results of `fetchAll` calls keyed by their params, see `fetchAllIfNeeded`. */
private fetchAllResults = new Map<string, PaginatedResponse<T>>();
}