[9.0] [embeddable] fix race condition in useBatchedPublishingSubjects (#216399) (#216527)

# Backport

This will backport the following commits from `main` to `9.0`:
- [[embeddable] fix race condition in useBatchedPublishingSubjects
(#216399)](https://github.com/elastic/kibana/pull/216399)

<!--- Backport version: 9.6.6 -->

### Questions ?
Please refer to the [Backport tool
documentation](https://github.com/sorenlouv/backport)

<!--BACKPORT [{"author":{"name":"Nathan
Reese","email":"reese.nathan@elastic.co"},"sourceCommit":{"committedDate":"2025-03-31T17:21:56Z","message":"[embeddable]
fix race condition in useBatchedPublishingSubjects (#216399)\n\nCloses
https://github.com/elastic/kibana/issues/214176
and\nhttps://github.com/elastic/kibana/issues/214853\n\n[upgrade from
chrome 134 to 135 in functional
test\nrunner](https://github.com/elastic/kibana/issues/213919) revealed
a race\ncondition in `useBatchedPublishingSubjects` where batched
observables\ncould emit new values before `useEffect` sets up the
subscription. This\nPR resolves this issue by setting up subscription in
useRef, which has\nno timing delays.\n\nIn chrome 134,
`useBatchedPublishingSubjects` `useEffect` gets called\n(setting up
subscription) before lens embeddable emits any changes to\nbatched
observables.\n<img width=\"300\"
alt=\"chrome134\"\nsrc=\"https://github.com/user-attachments/assets/b0356f74-e0c7-4d93-a23a-ace519194d5d\"\n/>\n\nIn
chrome 135, `useBatchedPublishingSubjects` `useEffect` gets
called\nafter lens embeddable emits changes to batched observables. This
causes\nthe lens embeddable to not render since the
`LensEmbeddableComponent`\nhas a stale value for
`expressionParams`.\n<img width=\"300\"
alt=\"chrome135\"\nsrc=\"https://github.com/user-attachments/assets/320bfb7e-8b3f-4b48-a138-1c47c5ff9961\"\n/>\n\n---------\n\nCo-authored-by:
Elastic Machine
<elasticmachine@users.noreply.github.com>\nCo-authored-by: kibanamachine
<42973632+kibanamachine@users.noreply.github.com>","sha":"f408a513dd5fdecf5ebbc4e3265e1b998421d39b","branchLabelMapping":{"^v9.1.0$":"main","^v8.19.0$":"8.x","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["release_note:fix","Team:Presentation","backport:version","v8.18.0","v9.1.0","v8.19.0","v9.0.1","v8.17.5","v8.16.7"],"title":"[embeddable]
fix race condition in
useBatchedPublishingSubjects","number":216399,"url":"https://github.com/elastic/kibana/pull/216399","mergeCommit":{"message":"[embeddable]
fix race condition in useBatchedPublishingSubjects (#216399)\n\nCloses
https://github.com/elastic/kibana/issues/214176
and\nhttps://github.com/elastic/kibana/issues/214853\n\n[upgrade from
chrome 134 to 135 in functional
test\nrunner](https://github.com/elastic/kibana/issues/213919) revealed
a race\ncondition in `useBatchedPublishingSubjects` where batched
observables\ncould emit new values before `useEffect` sets up the
subscription. This\nPR resolves this issue by setting up subscription in
useRef, which has\nno timing delays.\n\nIn chrome 134,
`useBatchedPublishingSubjects` `useEffect` gets called\n(setting up
subscription) before lens embeddable emits any changes to\nbatched
observables.\n<img width=\"300\"
alt=\"chrome134\"\nsrc=\"https://github.com/user-attachments/assets/b0356f74-e0c7-4d93-a23a-ace519194d5d\"\n/>\n\nIn
chrome 135, `useBatchedPublishingSubjects` `useEffect` gets
called\nafter lens embeddable emits changes to batched observables. This
causes\nthe lens embeddable to not render since the
`LensEmbeddableComponent`\nhas a stale value for
`expressionParams`.\n<img width=\"300\"
alt=\"chrome135\"\nsrc=\"https://github.com/user-attachments/assets/320bfb7e-8b3f-4b48-a138-1c47c5ff9961\"\n/>\n\n---------\n\nCo-authored-by:
Elastic Machine
<elasticmachine@users.noreply.github.com>\nCo-authored-by: kibanamachine
<42973632+kibanamachine@users.noreply.github.com>","sha":"f408a513dd5fdecf5ebbc4e3265e1b998421d39b"}},"sourceBranch":"main","suggestedTargetBranches":["8.18","8.x","9.0","8.17","8.16"],"targetPullRequestStates":[{"branch":"8.18","label":"v8.18.0","branchLabelMappingKey":"^v(\\d+).(\\d+).\\d+$","isSourceBranch":false,"state":"NOT_CREATED"},{"branch":"main","label":"v9.1.0","branchLabelMappingKey":"^v9.1.0$","isSourceBranch":true,"state":"MERGED","url":"https://github.com/elastic/kibana/pull/216399","number":216399,"mergeCommit":{"message":"[embeddable]
fix race condition in useBatchedPublishingSubjects (#216399)\n\nCloses
https://github.com/elastic/kibana/issues/214176
and\nhttps://github.com/elastic/kibana/issues/214853\n\n[upgrade from
chrome 134 to 135 in functional
test\nrunner](https://github.com/elastic/kibana/issues/213919) revealed
a race\ncondition in `useBatchedPublishingSubjects` where batched
observables\ncould emit new values before `useEffect` sets up the
subscription. This\nPR resolves this issue by setting up subscription in
useRef, which has\nno timing delays.\n\nIn chrome 134,
`useBatchedPublishingSubjects` `useEffect` gets called\n(setting up
subscription) before lens embeddable emits any changes to\nbatched
observables.\n<img width=\"300\"
alt=\"chrome134\"\nsrc=\"https://github.com/user-attachments/assets/b0356f74-e0c7-4d93-a23a-ace519194d5d\"\n/>\n\nIn
chrome 135, `useBatchedPublishingSubjects` `useEffect` gets
called\nafter lens embeddable emits changes to batched observables. This
causes\nthe lens embeddable to not render since the
`LensEmbeddableComponent`\nhas a stale value for
`expressionParams`.\n<img width=\"300\"
alt=\"chrome135\"\nsrc=\"https://github.com/user-attachments/assets/320bfb7e-8b3f-4b48-a138-1c47c5ff9961\"\n/>\n\n---------\n\nCo-authored-by:
Elastic Machine
<elasticmachine@users.noreply.github.com>\nCo-authored-by: kibanamachine
<42973632+kibanamachine@users.noreply.github.com>","sha":"f408a513dd5fdecf5ebbc4e3265e1b998421d39b"}},{"branch":"8.x","label":"v8.19.0","branchLabelMappingKey":"^v8.19.0$","isSourceBranch":false,"state":"NOT_CREATED"},{"branch":"9.0","label":"v9.0.1","branchLabelMappingKey":"^v(\\d+).(\\d+).\\d+$","isSourceBranch":false,"state":"NOT_CREATED"},{"branch":"8.17","label":"v8.17.5","branchLabelMappingKey":"^v(\\d+).(\\d+).\\d+$","isSourceBranch":false,"state":"NOT_CREATED"},{"branch":"8.16","label":"v8.16.7","branchLabelMappingKey":"^v(\\d+).(\\d+).\\d+$","isSourceBranch":false,"state":"NOT_CREATED"}]}]
BACKPORT-->

Co-authored-by: Nathan Reese <reese.nathan@elastic.co>
This commit is contained in:
Kibana Machine 2025-03-31 21:06:24 +02:00 committed by GitHub
parent bb3ac40a5c
commit eff6a4e353
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 52 additions and 13 deletions

View file

@ -7,7 +7,7 @@
* License v3.0 only", or the "Server Side Public License, v 1".
*/
import { useEffect, useRef, useState } from 'react';
import { useEffect, useMemo, useRef, useState } from 'react';
import { combineLatest, debounceTime, skip } from 'rxjs';
import { AnyPublishingSubject, PublishingSubject, UnwrapPublishingSubjectTuple } from './types';
@ -120,22 +120,37 @@ export const useBatchedPublishingSubjects = <
/**
* Subscribe to all subjects and update the latest values when any of them change.
*
* Can not set up subscription in useEffect.
* useEffect introduces a race condition where subscriptions may emit after values are set with useState
* but before subscription is setup in useEffect.
*
* Can not set up subscription in useRef.
* useRef executes initialization logic every render.
*/
useEffect(() => {
const subscription = combineLatest(subjects)
.pipe(
// When a new observer subscribes to a BehaviorSubject, it immediately receives the current value. Skip this emit.
skip(1),
debounceTime(0)
)
.subscribe((values) => {
setLatestPublishedValues(values as UnwrapPublishingSubjectTuple<SubjectsType>);
});
return () => subscription.unsubscribe();
const subscription = useMemo(
() =>
combineLatest(subjects)
.pipe(
// When a new observer subscribes to a BehaviorSubject, it immediately receives the current value. Skip this emit.
skip(1),
debounceTime(0)
)
.subscribe((values) => {
setLatestPublishedValues(values as UnwrapPublishingSubjectTuple<SubjectsType>);
}),
// 'subjects' gets a new reference on each call because of spread
// Use 'useBatchedOptionalPublishingSubjects' when 'subjects' are expected to change.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
[]
);
/**
* Clean up subscription on unmount.
*/
useEffect(() => {
return () => subscription.unsubscribe();
}, [subscription]);
return latestPublishedValues;
};

View file

@ -118,6 +118,30 @@ describe('publishing subject', () => {
expect(renderCount).toBe(2);
});
test('useBatchedPublishingSubjects should synchronously subscribe to observables to avoid race conditions', async () => {
function Component() {
const [value1] = useBatchedPublishingSubjects(subject1);
// synchronously emit new values for observables
// this will cause test to fail if subscriptions are not setup synchronously
incrementAll();
return (
<>
<span>{`value1: ${value1}`}</span>
</>
);
}
render(<Component />);
await waitFor(() => {
expect(
// If there is a race condition, then 'value1: 0' will be rendered
// because value1 will have the original value '0' instead of latest value
screen.getByText('value1: 1')
).toBeInTheDocument();
});
});
test('should batch state updates when using useBatchedOptionalPublishingSubjects', async () => {
let renderCount = 0;
function Component() {