Skip to content

Commit 17ea655

Browse files
committed
refactor(sdk): simplify flag update notifications and subscriptions
1 parent db4af1e commit 17ea655

4 files changed

Lines changed: 96 additions & 61 deletions

File tree

‎packages/browser-sdk/src/flag/flags.ts‎

Lines changed: 28 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -397,25 +397,21 @@ export class FlagsClient {
397397
this.flagOverrides = { ...cachedOverrides, ...this.flagOverrides };
398398
}
399399

400-
if (!this.bootstrapped) {
400+
if (this.bootstrapped) {
401+
// Apply cached overrides silently, then publish each initial value once.
402+
const previousFlags = this.flags;
403+
this.updateFlags(false);
404+
const rawFlagsChanged = previousFlags !== this.flags;
405+
this.triggerFlagUpdates({});
406+
if (rawFlagsChanged) this.triggerFlagsUpdated();
407+
} else {
401408
const requestContextVersion = this.contextFetchVersion;
402409
this.applyFetchedFlagsResult(
403410
await this.maybeFetchFlags(requestContextVersion),
404411
true,
405412
requestContextVersion,
406413
);
407-
}
408-
409-
// Apply overrides before publishing initial bootstrapped values. Suppress
410-
// change events here so overridden flags are not published twice.
411-
const previousFlags = this.flags;
412-
this.updateFlags(!this.bootstrapped);
413-
const flagsChanged = previousFlags !== this.flags;
414-
if (this.bootstrapped) {
415-
for (const [key, flag] of Object.entries(this.flags)) {
416-
this.triggerFlagUpdated({ key, flag });
417-
}
418-
if (flagsChanged) this.triggerFlagsUpdated();
414+
this.updateFlags();
419415
}
420416
initializationSucceeded = true;
421417
} finally {
@@ -656,27 +652,11 @@ export class FlagsClient {
656652
const updatedFlags = this.mergeFlags(this.fetchedFlags, this.flagOverrides);
657653
// Nothing has changed, skipping update
658654
if (deepEqual(this.flags, updatedFlags)) return;
659-
const updates: FlagUpdatedEvent[] = [];
660-
if (triggerEvent) {
661-
const keys = new Set([
662-
...Object.keys(this.flags),
663-
...Object.keys(updatedFlags),
664-
]);
665-
for (const key of keys) {
666-
const previous = Object.prototype.hasOwnProperty.call(this.flags, key)
667-
? this.flags[key]
668-
: undefined;
669-
const flag = Object.prototype.hasOwnProperty.call(updatedFlags, key)
670-
? updatedFlags[key]
671-
: undefined;
672-
if (flagValueChanged(previous, flag)) updates.push({ key, flag });
673-
}
674-
}
675-
655+
const previousFlags = this.flags;
676656
this.flags = updatedFlags;
677657
if (triggerEvent) {
678-
// Raw-data subscribers may synchronously change overrides again.
679-
for (const update of updates) this.triggerFlagUpdated(update);
658+
// Publish values before raw-data subscribers can change overrides again.
659+
this.triggerFlagUpdates(previousFlags);
680660
this.triggerFlagsUpdated();
681661
}
682662
}
@@ -1055,8 +1035,22 @@ export class FlagsClient {
10551035
return mergedFlags;
10561036
}
10571037

1058-
private triggerFlagUpdated(event: FlagUpdatedEvent) {
1059-
for (const callback of this.flagUpdatedListeners) callback(event);
1038+
private triggerFlagUpdates(previousFlags: RawFlags) {
1039+
// Maps distinguish missing flags from inherited properties such as constructor.
1040+
const previous = new Map(Object.entries(previousFlags));
1041+
const current = new Map(Object.entries(this.flags));
1042+
const keys = new Set([...previous.keys(), ...current.keys()]);
1043+
const updates: FlagUpdatedEvent[] = [];
1044+
for (const key of keys) {
1045+
const flag = current.get(key);
1046+
if (flagValueChanged(previous.get(key), flag))
1047+
updates.push({ key, flag });
1048+
}
1049+
1050+
// Capture the whole batch before callbacks can synchronously change flags.
1051+
for (const update of updates) {
1052+
for (const callback of this.flagUpdatedListeners) callback(update);
1053+
}
10601054
}
10611055

10621056
private triggerFlagsUpdated() {

‎packages/browser-sdk/test/flagUpdated.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,22 @@ describe("flagUpdated", () => {
435435
).toEqual([false, true]);
436436
});
437437

438+
test("removed flags with inherited Object property names have undefined payloads", () => {
439+
const client = newClient({
440+
constructor: { key: "constructor", isEnabled: false },
441+
toString: { key: "toString", isEnabled: false },
442+
});
443+
const listener = vi.fn();
444+
client.on("flagUpdated", listener);
445+
446+
client.updateFlags({});
447+
448+
expect(listener.mock.calls.map(([event]) => event)).toEqual([
449+
{ key: "constructor", flag: undefined },
450+
{ key: "toString", flag: undefined },
451+
]);
452+
});
453+
438454
test("listeners can unsubscribe", () => {
439455
const flags = initialFlags();
440456
const client = newClient(flags);

‎packages/react-sdk/src/index.tsx‎

Lines changed: 20 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -727,20 +727,26 @@ export function useFlag<TKey extends FlagKey>(
727727
key: TKey;
728728
flag: RawFlag | undefined;
729729
}>(() => ({ client, key, flag: client.getFlags()[key] }));
730-
const snapshotRef = useRef(snapshot);
731-
const updateFlag = () => {
732-
const flag = client.getFlags()[key];
733-
const previous = snapshotRef.current;
734-
if (
735-
previous.client !== client ||
736-
previous.key !== key ||
737-
previous.flag !== flag
738-
) {
739-
const updated = { client, key, flag };
740-
snapshotRef.current = updated;
741-
setSnapshot(updated);
742-
}
743-
};
730+
useIsomorphicLayoutEffect(() => {
731+
let current = snapshot;
732+
const updateFlag = () => {
733+
const flag = client.getFlags()[key];
734+
if (
735+
current.client !== client ||
736+
current.key !== key ||
737+
current.flag !== flag
738+
) {
739+
current = { client, key, flag };
740+
setSnapshot(current);
741+
}
742+
};
743+
const unsubscribe = client.on("flagUpdated", (event) => {
744+
if (event.key === key) updateFlag();
745+
});
746+
// Subscribe before catching updates since render, including client/key changes.
747+
updateFlag();
748+
return unsubscribe;
749+
}, [client, key]);
744750
const config = useMemo(() => {
745751
const flag =
746752
snapshot.client === client && snapshot.key === key
@@ -755,19 +761,6 @@ export function useFlag<TKey extends FlagKey>(
755761
const requestFeedback = (opts: RequestFeedbackOptions) =>
756762
client.requestFeedback({ ...opts, flagKey: key });
757763

758-
useOnEvent(
759-
"flagUpdated",
760-
(event) => {
761-
if (event.key === key) updateFlag();
762-
},
763-
client,
764-
);
765-
766-
useIsomorphicLayoutEffect(() => {
767-
// Catch updates between rendering and subscribing, and changes of client/key.
768-
updateFlag();
769-
}, [client, key]);
770-
771764
if (
772765
isLoading &&
773766
isClientLoading(client) &&

‎packages/react-sdk/test/flag-updated.test.tsx‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -362,6 +362,38 @@ describe("useFlag value subscriptions", () => {
362362
unmount();
363363
});
364364

365+
test("keeps its subscription across value updates and parent rerenders", async () => {
366+
const flags = initialFlags();
367+
const client = await newClient(flags);
368+
const subscribe = vi.spyOn(client, "on");
369+
const renderSpy = vi.fn();
370+
const { result, rerender, unmount } = renderHook(
371+
() => {
372+
renderSpy();
373+
return useFlag("abc");
374+
},
375+
{ wrapper: wrapperFor(client) },
376+
);
377+
378+
rerender();
379+
act(() =>
380+
client.updateFlags({ ...flags, abc: { ...flags.abc, isEnabled: false } }),
381+
);
382+
act(() => client.updateFlags(flags));
383+
384+
expect(result.current.isEnabled).toBe(true);
385+
expect(
386+
subscribe.mock.calls.filter(([event]) => event === "flagUpdated"),
387+
).toHaveLength(1);
388+
389+
unmount();
390+
renderSpy.mockClear();
391+
act(() =>
392+
client.updateFlags({ ...flags, abc: { ...flags.abc, isEnabled: false } }),
393+
);
394+
expect(renderSpy).not.toHaveBeenCalled();
395+
});
396+
365397
test("catches an update between rendering and subscribing", async () => {
366398
const flags = initialFlags();
367399
const client = await newClient(flags);

0 commit comments

Comments
 (0)