Skip to content

Commit c5d882b

Browse files
totally-not-ai[bot]caalador
authored andcommitted
fix: run signal effects inline only when session is locked (#27460) (CP: 25.4)
Related to #27187, #27188 **Hardening** · flow-server · signal effects owned by a UI Signal effects, the signal result notifier and the background change flag treated "this UI is current" as "this thread holds the session lock". Flow's request handling now keeps that rule (#27201, #27439). Code outside Flow can still break it, for example by calling `UI.setCurrent` without locking the session. Then an effect touched UI state without the lock and failed with "Cannot access state in VaadinSession or UI without locking the session". After that, its error handler failed the same way. **Risks:** - ⚠️ Behaviour change, only when the UI is current but its session is not locked by this thread: the effect, or the result notifier task, is queued through `UI.access` instead of running right away. `isBackgroundChange()` reports `true` for that run. - When the UI is current and locked, which is every normal case, nothing changes. - ✅ No new public API. The shared check is `UIInternals.isCurrentAndLocked()`, which is in the internal package. The added cost is one `hasLock()` call. - `ElementEffect`, the result notifier in `VaadinService` and `Effect`'s background change flag use the new check. - `guidelines/architecture.md` now describes signal effects as checking the session lock instead of trusting the current UI. - Three existing `EffectTest` owner-UI tests now use a plain `UI` with a mocked session that reports the lock as held, instead of a Mockito `UI` mock. The owner UI's internals and session lock are now read, and a Mockito `UI` has no internals. They avoid `MockUI` because it starts a `VaadinService`, which registers a signal environment that stays active for the rest of the test class. - Tests: an effect and a result notifier task triggered while the owner UI is current but unlocked run later with the lock held, and the effect reports a background change. Both tests fail without the fix. Working on behalf of @Artur- --------- Co-authored-by: totally-not-ai[bot] <290682512+totally-not-ai[bot]@users.noreply.github.com> Co-authored-by: caalador <mikael.grankvist@vaadin.com>
1 parent a73ff5b commit c5d882b

8 files changed

Lines changed: 112 additions & 20 deletions

File tree

‎flow-server/src/main/java/com/vaadin/flow/component/internal/UIInternals.java‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1362,6 +1362,20 @@ public VaadinSession getSession() {
13621362
return session;
13631363
}
13641364

1365+
/**
1366+
* Checks whether the current thread may use the related UI directly: the UI
1367+
* is the current UI and the current thread holds the lock of its session.
1368+
* <p>
1369+
* The current UI alone is not enough, as code that sets the current UI
1370+
* without locking the session would otherwise use the UI without the lock.
1371+
*
1372+
* @return {@code true} if the related UI is the current UI and its session
1373+
* is locked by the current thread, {@code false} otherwise
1374+
*/
1375+
public boolean isCurrentAndLocked() {
1376+
return UI.getCurrent() == ui && session != null && session.hasLock();
1377+
}
1378+
13651379
private static Logger getLogger() {
13661380
return LoggerFactory.getLogger(UIInternals.class.getName());
13671381
}

‎flow-server/src/main/java/com/vaadin/flow/dom/ElementEffect.java‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -273,8 +273,8 @@ private void enableEffect(UI ui) {
273273
.error(new ErrorEvent(e, elem.getNode()));
274274

275275
SerializableExecutor uiDispatcher = command -> {
276-
if (UI.getCurrent() == ui) {
277-
// Run immediately if on the same UI
276+
if (ui.getInternals().isCurrentAndLocked()) {
277+
// Run immediately if on the same UI with its session locked
278278
command.run();
279279
} else {
280280
SignalEnvironment.getDefaultEffectDispatcher().execute(() -> {
@@ -283,10 +283,10 @@ private void enableEffect(UI ui) {
283283
if (effect != null) {
284284
// In test environments, the effect dispatcher
285285
// may run tasks on the test thread where
286-
// UI.getCurrent() is already set. In that case
286+
// the UI is current and locked. In that case
287287
// run directly instead of ui.access() which
288288
// would only enqueue without executing.
289-
if (UI.getCurrent() == ui) {
289+
if (ui.getInternals().isCurrentAndLocked()) {
290290
command.run();
291291
} else {
292292
ui.access(command::run);

‎flow-server/src/main/java/com/vaadin/flow/server/VaadinService.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -543,7 +543,7 @@ private Executor createCurrentUiDispatcher() {
543543
}
544544

545545
return task -> {
546-
if (UI.getCurrent() == owner) {
546+
if (owner.getInternals().isCurrentAndLocked()) {
547547
task.run();
548548
} else {
549549
try {

‎flow-server/src/main/java/com/vaadin/flow/signals/impl/Effect.java‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -271,7 +271,8 @@ private boolean onDependencyChange(boolean immediate) {
271271
}
272272

273273
if (ownerUI != null) {
274-
invalidatedFromBackground = UI.getCurrent() != ownerUI;
274+
invalidatedFromBackground = !ownerUI.getInternals()
275+
.isCurrentAndLocked();
275276
} else {
276277
invalidatedFromBackground = VaadinRequest.getCurrent() == null;
277278
}
@@ -324,10 +325,10 @@ private List<Registration> drainRegistrations() {
324325

325326
/**
326327
* Sets the owner UI for this effect. When set, background change detection
327-
* compares {@link UI#getCurrent()} against this UI instead of only checking
328-
* for the presence of a {@link VaadinRequest}. This allows effects to
329-
* correctly detect changes triggered by another user's session on a shared
330-
* signal.
328+
* checks that this UI is the current UI and that its session is locked by
329+
* the current thread, instead of only checking for the presence of a
330+
* {@link VaadinRequest}. This allows effects to correctly detect changes
331+
* triggered by another user's session on a shared signal.
331332
*
332333
* @param ui
333334
* the owner UI, or {@code null} to fall back to

‎flow-server/src/test/java/com/vaadin/flow/dom/ElementEffectTest.java‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -458,6 +458,41 @@ void effect_triggeredWithOtherUILocked_effectRunAsynchronously() {
458458
"Effect should run with correct UI context");
459459
}
460460

461+
@Test
462+
void effect_triggeredWithOwnerUICurrentButSessionUnlocked_effectRunWithLock() {
463+
// The UI stays current after the session lock is released, e.g.
464+
// when custom code sets the current UI without locking
465+
CurrentInstance.clearAll();
466+
VaadinService.setCurrent(service);
467+
468+
var session = new MockVaadinSession(service);
469+
session.lock();
470+
VaadinSession.setCurrent(session);
471+
var ui = new MockUI(session);
472+
473+
ValueSignal<String> signal = new ValueSignal<>("initial");
474+
List<Boolean> lockedDuringRun = new ArrayList<>();
475+
List<Boolean> backgroundChanges = new ArrayList<>();
476+
Signal.effect(ui, ctx -> {
477+
signal.get();
478+
lockedDuringRun.add(session.hasLock());
479+
backgroundChanges.add(ctx.isBackgroundChange());
480+
});
481+
session.unlock();
482+
assertSame(ui, UI.getCurrent());
483+
484+
signal.set("changed");
485+
assertEquals(List.of(true), lockedDuringRun,
486+
"Effect must not run inline without the session lock");
487+
488+
service.flushExecutorAndAccessTasks(session);
489+
490+
assertEquals(List.of(true, true), lockedDuringRun,
491+
"Effect should run once more with the session lock held");
492+
assertEquals(List.of(false, true), backgroundChanges,
493+
"Change made without the session lock is a background change");
494+
}
495+
461496
@Test
462497
void effect_sharedSignalUpdatedOutsideSessionTransaction_reRunsWithFreshValue() {
463498
// Reproduces issue #24399: while a UIDL request holds the session

‎flow-server/src/test/java/com/vaadin/flow/server/VaadinServiceSignalsInitializationTest.java‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,33 @@ record EffectExecution(UI ui, String threadName) {
107107
"Expected effect to be executed in Vaadin Executor thread");
108108
}
109109

110+
@Test
111+
void resultNotifier_ownerUiCurrentButSessionUnlocked_taskRunWithLock()
112+
throws InterruptedException {
113+
var service = new MockVaadinServletService();
114+
VaadinService.setCurrent(service);
115+
116+
var session = new MockVaadinSession(service);
117+
session.lock();
118+
var ui = new MockUI(session);
119+
var dispatcher = SignalEnvironment.getCurrentResultNotifier();
120+
session.unlock();
121+
// Like after a request has released the session lock
122+
assertSame(ui, UI.getCurrent());
123+
124+
AtomicBoolean lockedDuringRun = new AtomicBoolean();
125+
CountDownLatch latch = new CountDownLatch(1);
126+
dispatcher.execute(() -> {
127+
lockedDuringRun.set(session.hasLock());
128+
latch.countDown();
129+
});
130+
131+
assertTrue(latch.await(500, TimeUnit.MILLISECONDS),
132+
"Expected task to be executed");
133+
assertTrue(lockedDuringRun.get(),
134+
"Expected task to run with the session lock held");
135+
}
136+
110137
@Test
111138
void resultNotifier_ownerUiIsClosing_taskNotScheduled()
112139
throws InterruptedException {

‎flow-server/src/test/java/com/vaadin/flow/signals/impl/EffectTest.java‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
import com.vaadin.flow.function.SerializableExecutor;
3535
import com.vaadin.flow.internal.CurrentInstance;
3636
import com.vaadin.flow.server.VaadinRequest;
37+
import com.vaadin.flow.server.VaadinSession;
3738
import com.vaadin.flow.shared.Registration;
3839
import com.vaadin.flow.signals.MissingSignalUsageException;
3940
import com.vaadin.flow.signals.Signal;
@@ -52,6 +53,7 @@
5253
import static org.junit.jupiter.api.Assertions.assertTrue;
5354
import static org.junit.jupiter.api.Assertions.fail;
5455
import static org.mockito.Mockito.mock;
56+
import static org.mockito.Mockito.when;
5557

5658
class EffectTest extends SignalTestBase {
5759

@@ -841,7 +843,7 @@ public Registration onNextChange(
841843

842844
@Test
843845
void ownerUI_sameUICurrent_notBackgroundChange() {
844-
UI ui = mock(UI.class);
846+
UI ui = createLockedUI();
845847
UI.setCurrent(ui);
846848

847849
ValueSignal<String> signal = new ValueSignal<>("hello");
@@ -865,7 +867,7 @@ void ownerUI_sameUICurrent_notBackgroundChange() {
865867

866868
@Test
867869
void ownerUI_noUICurrent_isBackgroundChange() {
868-
UI ui = mock(UI.class);
870+
UI ui = createLockedUI();
869871
UI.setCurrent(ui);
870872

871873
ValueSignal<String> signal = new ValueSignal<>("hello");
@@ -889,8 +891,8 @@ void ownerUI_noUICurrent_isBackgroundChange() {
889891

890892
@Test
891893
void ownerUI_differentUICurrent_isBackgroundChange() {
892-
UI uiA = mock(UI.class);
893-
UI uiB = mock(UI.class);
894+
UI uiA = createLockedUI();
895+
UI uiB = createLockedUI();
894896

895897
ValueSignal<String> signal = new ValueSignal<>("initial");
896898
List<Boolean> backgroundChangesA = new ArrayList<>();
@@ -1473,6 +1475,19 @@ void concurrentRevalidations_latestGenerationWins() throws Exception {
14731475
"effect did not react to signalB; it kept a stale dependency set");
14741476
}
14751477

1478+
/**
1479+
* Creates a UI whose session reports the lock as held by the current
1480+
* thread, without a VaadinService behind it so that no Vaadin signal
1481+
* environment gets registered.
1482+
*/
1483+
private static UI createLockedUI() {
1484+
VaadinSession session = mock(VaadinSession.class);
1485+
when(session.hasLock()).thenReturn(true);
1486+
UI ui = new UI();
1487+
ui.getInternals().setSession(session);
1488+
return ui;
1489+
}
1490+
14761491
private static void await(CountDownLatch latch) {
14771492
try {
14781493
latch.await();

‎guidelines/architecture.md‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -106,12 +106,12 @@ The rules are in the Session Lock and Current Instances section of
106106

107107
`UI.getCurrent()` is a promise to the code that reads it: the UI is safe to
108108
touch from this thread right now. Application code relies on that promise
109-
without checking it, and so does the framework — a signal effect, for example,
110-
treats a signal change made on a thread where its UI is current as a change
111-
made inside that UI's locked work, and handles it without going through
112-
`UI.access`. A current UI without the lock breaks that promise silently: the
113-
code mutates the state tree concurrently with the thread that does hold the
114-
lock, and nothing fails until the data is corrupted.
109+
without checking it. A current UI without the lock breaks that promise
110+
silently: the code mutates the state tree concurrently with the thread that
111+
does hold the lock, and nothing fails until the data is corrupted. Signal
112+
effects are the exception: they run inline only when their UI is current and
113+
its session is locked by this thread, and otherwise go through `UI.access`, so
114+
they stay correct even when the promise is broken.
115115

116116
`UI.accessSynchronously` and `VaadinSession.accessSynchronously` show the shape
117117
to copy: lock the session, set the current instances with

0 commit comments

Comments
 (0)