Skip to content

Commit 9600479

Browse files
brenelzryansolidclaude
authored
fix: apply the action response inside the transition so revalidation and the optimistic release commit as one frame (#621)
* fix: revalidate inside the action transition so optimistic writes revert * test: cover redirects and poll instead of fixed waits in #620 spec * test: assert the revert and the refetch commit as one frame; reword for #619 On solid-js rc.11 the "#620 never reverts" symptom is fixed upstream (solidjs/solid#3663, #3674): the existing revert tests pass on `next` without the src change. What the change still fixes is that the optimistic overlay released when the inner action's transition committed, before the revalidation refetch landed, so the rows re-rendered against stale query data in between. The new spec drives every fetch and the action through deferreds and records committed DOM frames with a MutationObserver: three rows through `<For>`, an optimistic store write in a solid `action`, and a router `action` that returns an Error, leaves the data unchanged, commits the swap, or commits the swap plus a change the optimistic write did not predict. It asserts the exact frame sequence — [optimistic, truth] with the revert held until the refetch resolves, or [optimistic] alone when the server confirms it. All four fail on `next` src with the torn `b1/0 a0/1 c2/2` frame committed before the refetch, and pass with the fix. Changeset and src comment reworded to describe the atomic commit rather than "never reverts", referencing #619. Co-authored-by: Claude <[email protected]> --------- Co-authored-by: Ryan Carniato <[email protected]> Co-authored-by: Claude <[email protected]>
1 parent 0db63bf commit 9600479

4 files changed

Lines changed: 332 additions & 20 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@solidjs/router": patch
3+
---
4+
5+
A router action's default revalidation now runs inside the action's transition, so the refetch and the release of the caller's optimistic writes commit as one frame. The response used to be applied after the inner Solid action had settled: the optimistic overlay released when that action's transition committed while the refetch was still in flight, so the rows re-rendered against stale query data until it landed — a torn frame when the server rejected the change, and a flash away from and back to the optimistic result when it committed the change (#619).

‎src/data/action.ts‎

Lines changed: 27 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -260,18 +260,26 @@ function actionImpl<T extends Array<any>, U = void>(
260260
optimistic?: () => void;
261261
}) {
262262
context.optimistic?.();
263+
let value: unknown;
264+
let error = false;
263265
try {
264-
const value = await context.call();
265-
yield;
266-
return { error: false, value };
267-
} catch (error) {
268-
yield;
269-
return { error: true, value: error };
266+
value = await context.call();
267+
} catch (e) {
268+
value = e;
269+
error = true;
270270
}
271+
const read = await readResponse(value, error);
272+
yield;
273+
// Apply inside the transition so the default revalidation's refetch and
274+
// the release of the caller's optimistic writes commit as one frame (#619).
275+
return applyResponse(
276+
read,
277+
router.navigatorFactory(),
278+
flightApplications !== flightApplicationsBefore
279+
);
271280
});
272281

273282
form && setFormBusy(form, 1);
274-
let settled;
275283
let response;
276284
// The transport consumer is awaited before a single-flight mutation
277285
// resolves, so a counter delta over the call tells whether this action's
@@ -281,7 +289,7 @@ function actionImpl<T extends Array<any>, U = void>(
281289
// which misses every response the server returned without flight data.
282290
const flightApplicationsBefore = flightApplications;
283291
try {
284-
settled = await settleActionResult(
292+
response = await settleActionResult(
285293
run({
286294
call: runMutation,
287295
optimistic: submitHooks.size
@@ -291,12 +299,6 @@ function actionImpl<T extends Array<any>, U = void>(
291299
: undefined
292300
})
293301
);
294-
response = await handleResponse(
295-
settled.value,
296-
settled.error,
297-
router.navigatorFactory(),
298-
flightApplications !== flightApplicationsBefore
299-
);
300302
} finally {
301303
form && setFormBusy(form, -1);
302304
}
@@ -511,12 +513,11 @@ function applyResponseMetadata(
511513
revalidate(keys, false);
512514
}
513515

514-
async function handleResponse(
515-
response: unknown,
516-
error: boolean | undefined,
517-
navigate: Navigator,
518-
metadataHandled: boolean
519-
) {
516+
type ReadResponse =
517+
| { error: unknown }
518+
| { data?: any; flightData?: Record<string, any>; metadata?: Response };
519+
520+
async function readResponse(response: unknown, error: boolean): Promise<ReadResponse> {
520521
let data: any;
521522
let flightData: Record<string, any> | undefined;
522523
let metadata: Response | undefined;
@@ -538,6 +539,12 @@ async function handleResponse(
538539
}
539540
} else if (error) return { error: response };
540541
else data = response;
542+
return { data, flightData, metadata };
543+
}
544+
545+
function applyResponse(read: ReadResponse, navigate: Navigator, metadataHandled: boolean) {
546+
if ("error" in read) return read;
547+
const { data, flightData, metadata } = read;
541548
// The transport consumer applies metadata before returning a server
542549
// function's unwrapped value. Do not treat that value as a second plain
543550
// action response and invalidate the freshly seeded query cache again.
Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
// @vitest-environment jsdom
2+
import { action, createMemo, createOptimisticStore, For, Loading } from "solid-js";
3+
import { render } from "@solidjs/web";
4+
import {
5+
action as routerAction,
6+
createRouter,
7+
memoryHistory,
8+
query,
9+
useAction
10+
} from "../src/index.js";
11+
12+
// A router action's default revalidation must commit together with the
13+
// caller's optimistic overlay release. Before #621 `handleResponse` ran after
14+
// the inner Solid action had settled, so the overlay released when that
15+
// action's transition committed while the refetch it started was still in
16+
// flight: the rows re-rendered against the stale query data in between (#619).
17+
//
18+
// Every fetch and the action itself resolve through deferreds owned by the
19+
// test, and committed frames are recorded from a MutationObserver, so the
20+
// assertions are on the exact sequence of DOM commits, not on timing.
21+
22+
type Card = { id: string; order: number };
23+
24+
function deferred<T>() {
25+
let resolve!: (value: T) => void;
26+
const promise = new Promise<T>(r => (resolve = r));
27+
return { promise, resolve };
28+
}
29+
30+
// Drain microtasks and a few macrotasks so every settled promise has flushed.
31+
const settle = async (turns = 3) => {
32+
for (let i = 0; i < turns; i++) await new Promise(r => setTimeout(r, 0));
33+
};
34+
35+
function observeFrames(root: HTMLElement) {
36+
const frames: string[] = [];
37+
const observer = new MutationObserver(() => frames.push(root.textContent!));
38+
observer.observe(root, { childList: true, characterData: true, subtree: true });
39+
return { frames, disconnect: () => observer.disconnect() };
40+
}
41+
42+
async function textBecomes(root: HTMLElement, text: string) {
43+
for (let i = 0; i < 100 && root.textContent !== text; i++) await settle(1);
44+
expect(root.textContent).toBe(text);
45+
}
46+
47+
function setup(label: string, serverSide: (db: Card[]) => unknown) {
48+
const db: Card[] = [
49+
{ id: "a", order: 0 },
50+
{ id: "b", order: 1 },
51+
{ id: "c", order: 2 }
52+
];
53+
const fetches: ReturnType<typeof deferred<Card[]>>[] = [];
54+
const getCards = query(() => {
55+
const d = deferred<Card[]>();
56+
fetches.push(d);
57+
return d.promise;
58+
}, `cards-621-${label}`);
59+
const settleFetch = (i: number) => fetches[i].resolve(db.map(c => ({ ...c })));
60+
61+
const server = deferred<void>();
62+
const swapOnServer = routerAction(async () => {
63+
await server.promise;
64+
return serverSide(db);
65+
}, `swap-621-${label}`);
66+
67+
let swap!: () => Promise<unknown>;
68+
const Cards = () => {
69+
const data = createMemo(() => getCards());
70+
const [cards, setCards] = createOptimisticStore(() => data(), [] as Card[]);
71+
const call = useAction(swapOnServer);
72+
swap = action(function* () {
73+
setCards(list => {
74+
const t = list[0].order;
75+
list[0].order = list[1].order;
76+
list[1].order = t;
77+
});
78+
yield call();
79+
});
80+
const sorted = createMemo(() => [...cards].sort((x, y) => x.order - y.order));
81+
return (
82+
<ul>
83+
<For each={sorted()}>
84+
{(card, i) => (
85+
<li>
86+
{card.id}
87+
{card.order}/{i()}{" "}
88+
</li>
89+
)}
90+
</For>
91+
</ul>
92+
);
93+
};
94+
95+
const Router = createRouter({
96+
routes: [{ path: "/", component: Cards }] as const,
97+
history: memoryHistory("/")
98+
});
99+
const root = document.createElement("div");
100+
const dispose = render(
101+
() => <Router>{props => <Loading fallback="…">{props.children}</Loading>}</Router>,
102+
root
103+
);
104+
return { root, dispose, fetches, settleFetch, server, swap: () => swap() };
105+
}
106+
107+
const TRUTH = "a0/0 b1/1 c2/2 ";
108+
const OPTIMISTIC = "b0/0 a1/1 c2/2 ";
109+
110+
// Drives one submission: optimistic write, the action settles while the test
111+
// still holds the refetch it started, then the refetch lands. Returns the
112+
// frames committed between the optimistic write and the end.
113+
async function submit(
114+
t: ReturnType<typeof setup>,
115+
betweenSettleAndRefetch: (frames: string[]) => void
116+
) {
117+
t.settleFetch(0);
118+
await textBecomes(t.root, TRUTH);
119+
const { frames, disconnect } = observeFrames(t.root);
120+
121+
const done = t.swap();
122+
await settle();
123+
expect(frames).toEqual([OPTIMISTIC]);
124+
expect(t.fetches.length).toBe(1);
125+
126+
// The action settles; its default revalidation starts a refetch that the
127+
// test still holds.
128+
t.server.resolve();
129+
await settle();
130+
expect(t.fetches.length).toBe(2);
131+
betweenSettleAndRefetch(frames);
132+
133+
t.settleFetch(1);
134+
await done;
135+
await settle();
136+
disconnect();
137+
t.dispose();
138+
return frames;
139+
}
140+
141+
describe("#621 router action revalidation commits atomically with the optimistic release", () => {
142+
for (const [label, outcome] of [
143+
["returns an Error", () => new Error("rejected")],
144+
["leaves the data unchanged", () => undefined]
145+
] as const) {
146+
test(`${label}: exactly [optimistic, truth], the revert waits for the refetch`, async () => {
147+
const t = setup(label.replace(/\W+/g, "-"), outcome);
148+
const frames = await submit(t, frames => {
149+
// Nothing may commit until the refetch lands: the revert and the
150+
// refetched data are one frame.
151+
expect(frames).toEqual([OPTIMISTIC]);
152+
});
153+
expect(frames).toEqual([OPTIMISTIC, TRUTH]);
154+
});
155+
}
156+
157+
test("commits the change: exactly [optimistic], no intermediate frame", async () => {
158+
const t = setup("commits", db => {
159+
const t = db[0].order;
160+
db[0].order = db[1].order;
161+
db[1].order = t;
162+
});
163+
const frames = await submit(t, frames => expect(frames).toEqual([OPTIMISTIC]));
164+
// The refetch confirms the optimistic frame; the DOM never changed again.
165+
expect(frames).toEqual([OPTIMISTIC]);
166+
});
167+
168+
test("commits the change and more: exactly [optimistic, truth] with the refetched data", async () => {
169+
const t = setup("commits-more", db => {
170+
const t = db[0].order;
171+
db[0].order = db[1].order;
172+
db[1].order = t;
173+
db[2].order = 5;
174+
});
175+
const frames = await submit(t, frames => expect(frames).toEqual([OPTIMISTIC]));
176+
// The part the optimistic write did not predict arrives in the same
177+
// commit as the release — proof the refetch, not just the release, landed.
178+
expect(frames).toEqual([OPTIMISTIC, "b0/0 a1/1 c5/2 "]);
179+
});
180+
});
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
// @vitest-environment jsdom
2+
import { action, createMemo, createOptimisticStore, Loading } from "solid-js";
3+
import { redirect, render } from "@solidjs/web";
4+
import {
5+
action as routerAction,
6+
createRouter,
7+
memoryHistory,
8+
query,
9+
useAction
10+
} from "../src/index.js";
11+
12+
const wait = (ms: number) => new Promise(r => setTimeout(r, ms));
13+
14+
async function textBecomes(root: HTMLElement, text: string, timeout = 1000) {
15+
const start = Date.now();
16+
while (root.textContent !== text) {
17+
if (Date.now() - start > timeout)
18+
throw new Error(`expected "${text}", still "${root.textContent}"`);
19+
await wait(5);
20+
}
21+
}
22+
23+
type Card = { id: string; order: number };
24+
25+
describe("#620 optimistic write reverts when a router action resolves", () => {
26+
for (const [label, outcome] of [
27+
["an Error", () => new Error("rejected")],
28+
["a value", () => "ok"],
29+
["nothing", () => undefined]
30+
] as const) {
31+
test(`reverts after the action returns ${label}`, async () => {
32+
const db: Card[] = [
33+
{ id: "a", order: 0 },
34+
{ id: "b", order: 1 }
35+
];
36+
const getCards = query(async () => {
37+
await wait(5);
38+
return db.map(c => ({ ...c }));
39+
}, `cards-620-${label}`);
40+
const rejectSwap = routerAction(async () => {
41+
await wait(50);
42+
return outcome();
43+
}, `reject-swap-620-${label}`);
44+
45+
let swap!: () => Promise<unknown>;
46+
const Cards = () => {
47+
const data = createMemo(() => getCards());
48+
const [cards, setCards] = createOptimisticStore(() => data(), [] as Card[]);
49+
const call = useAction(rejectSwap);
50+
swap = action(function* () {
51+
setCards(list => {
52+
const t = list[0].order;
53+
list[0].order = list[1].order;
54+
list[1].order = t;
55+
});
56+
yield call();
57+
});
58+
return (
59+
<pre>
60+
{[...cards]
61+
.sort((x, y) => x.order - y.order)
62+
.map(c => c.id)
63+
.join("")}
64+
</pre>
65+
);
66+
};
67+
68+
const Router = createRouter({
69+
routes: [{ path: "/", component: Cards }] as const,
70+
history: memoryHistory("/")
71+
});
72+
const root = document.createElement("div");
73+
const dispose = render(
74+
() => <Router>{props => <Loading fallback="…">{props.children}</Loading>}</Router>,
75+
root
76+
);
77+
78+
await textBecomes(root, "ab");
79+
swap();
80+
await textBecomes(root, "ba");
81+
await textBecomes(root, "ab");
82+
dispose();
83+
});
84+
}
85+
});
86+
87+
describe("router action redirects applied inside the transition", () => {
88+
for (const kind of ["returned", "thrown"] as const) {
89+
test(`navigates on a ${kind} redirect`, async () => {
90+
const go = routerAction(async () => {
91+
await wait(5);
92+
if (kind === "thrown") throw redirect("/other");
93+
return redirect("/other");
94+
}, `redirect-620-${kind}`);
95+
96+
let call!: () => Promise<unknown>;
97+
const Home = () => {
98+
call = useAction(go);
99+
return <span>home</span>;
100+
};
101+
const Router = createRouter({
102+
routes: [
103+
{ path: "/", component: Home },
104+
{ path: "/other", component: () => <span>other</span> }
105+
] as const,
106+
history: memoryHistory("/")
107+
});
108+
const root = document.createElement("div");
109+
const dispose = render(
110+
() => <Router>{props => <Loading fallback="…">{props.children}</Loading>}</Router>,
111+
root
112+
);
113+
114+
await textBecomes(root, "home");
115+
await expect(call()).resolves.toBeUndefined();
116+
await textBecomes(root, "other");
117+
dispose();
118+
});
119+
}
120+
});

0 commit comments

Comments
 (0)