diff --git a/.changeset/subscription-resume.md b/.changeset/subscription-resume.md new file mode 100644 index 000000000000..feb9f0ac89c4 --- /dev/null +++ b/.changeset/subscription-resume.md @@ -0,0 +1,32 @@ +--- +'@data-client/core': patch +'@data-client/react': patch +'@data-client/vue': patch +--- + +Fix polling from `controller.subscribe()` staying stopped after `` hides `DataProvider` + +When [``](https://react.dev/reference/react/Activity) hid a `DataProvider`, +[SubscriptionManager](https://dataclient.io/docs/api/SubscriptionManager) stopped every polling subscription and +never restarted it. Subscriptions from [useSubscription()](https://dataclient.io/docs/api/useSubscription) already +recovered, because their component subscribes again. A subscription made with +[controller.subscribe()](https://dataclient.io/docs/api/Controller#subscribe) now resumes polling too. + +When a remounted `DataProvider` reuses the same Managers, SubscriptionManager now drops the subscriptions of the old +store, so the new store polls for itself. + +A custom [Subscription](https://dataclient.io/docs/api/SubscriptionManager#subscription) can add `init()` to resume +work that `cleanup()` stopped: + +```ts +class StreamSubscription implements Subscription { + // ... + cleanup() { + this.socket?.close(); + this.socket = undefined; + } + init() { + this.socket ??= this.connect(); + } +} +``` diff --git a/docs/core/api/SubscriptionManager.md b/docs/core/api/SubscriptionManager.md index 51dbaaff9c21..888d7f63db65 100644 --- a/docs/core/api/SubscriptionManager.md +++ b/docs/core/api/SubscriptionManager.md @@ -36,6 +36,7 @@ interface Subscription { add(frequency?: number): void; remove(frequency?: number): boolean; cleanup(): void; + init?(): void; } /** The static class that constructs Subscription */ @@ -58,7 +59,14 @@ more subscriptions after. This is used to clean up unused `Subscription`s. ### cleanup(): void -Provides any cleanup of dangling resources after Subscription is no longer in use. +Stops background work, like timers or connections. `SubscriptionManager` calls it when the Subscription is no longer +in use, and when the store pauses. + +### init?(): void + +Resumes background work that `cleanup()` stopped. `SubscriptionManager` calls it when the store resumes, for every +Subscription it still tracks. It must do nothing while the Subscription is already running. Without `init()`, a +Subscription that outlives a pause stays stopped. ### Included implementation @@ -68,7 +76,7 @@ Provides any cleanup of dangling resources after Subscription is no longer in us Implementing your own `Subscription` to handle websockets can be done by [dispatching](./Controller.md#set) `rdc/set` actions with the data it gets to update. -Be sure to handle connection opening in the constructor and close the connection -in `cleanup()` +Be sure to handle connection opening in the constructor, close the connection +in `cleanup()`, and reopen it in `init()` ::: diff --git a/packages/core/src/manager/DevtoolsManager.ts b/packages/core/src/manager/DevtoolsManager.ts index 626e92a5ee3a..36bdb8495e77 100644 --- a/packages/core/src/manager/DevtoolsManager.ts +++ b/packages/core/src/manager/DevtoolsManager.ts @@ -229,8 +229,11 @@ export default class DevToolsManager implements Manager { /* istanbul ignore next */ if (process.env.NODE_ENV !== 'production') { this.prototype.middleware = function (controller) { - // a reused manager starts a fresh log for a new store - if (controller !== this.controller) this.actionLog = []; + // a reused manager starts fresh for a new store; SubscriptionManager drops its polls too + if (controller !== this.controller) { + this.actionLog = []; + this.pollingSubscribers = new Map(); + } this.controller = controller; const reducer = getExtension() && createReducer(controller as any); let state = controller.getState(); @@ -268,6 +271,8 @@ export default class DevToolsManager implements Manager { if (old >= 0) log[old] = summarize(log[old]); }; return next => action => { + // an unmounted store sharing this manager must not touch the new store's log + if (controller !== this.controller) return next(action); const shouldSkip = this.skipLogging?.(action); trackPolling(action); if (!shouldSkip) logAction(action); @@ -367,8 +372,6 @@ export default class DevToolsManager implements Manager { if (process.env.NODE_ENV !== 'production') { this.unsubscribeExtension?.(); this.unsubscribeExtension = undefined; - // SubscriptionManager.cleanup() stops polling without dispatching unsubscribes - this.pollingSubscribers.clear(); const key = this.registryKey; const registry: DebugStore['registry'] | undefined = (globalThis as any) .__DC__?.registry; diff --git a/packages/core/src/manager/PollingSubscription.ts b/packages/core/src/manager/PollingSubscription.ts index efb5ca023b24..f4b32c29d969 100644 --- a/packages/core/src/manager/PollingSubscription.ts +++ b/packages/core/src/manager/PollingSubscription.ts @@ -24,6 +24,8 @@ export default class PollingSubscription implements Subscription { declare protected lastIntervalId?: ReturnType; declare protected startId?: ReturnType; declare private connectionListener: ConnectionListener; + /** Stopped by `cleanup()` until `init()` */ + private stopped = false; constructor( action: Omit, @@ -42,6 +44,17 @@ export default class PollingSubscription implements Subscription { connectionListener || new DefaultConnectionListener(); // Kickstart running since this is initialized after the online notif is sent + this.start(); + } + + /** Resumes polling stopped by `cleanup()` */ + init() { + if (!this.stopped) return; + this.stopped = false; + this.start(); + } + + protected start() { if (this.connectionListener.isOnline()) { this.onlineListener(); } else { @@ -101,8 +114,13 @@ export default class PollingSubscription implements Subscription { return false; } - /** Cleanup means clearing out background interval. */ + /** Cleanup means clearing out background interval. `init()` resumes it. */ cleanup() { + this.stopped = true; + this.clear(); + } + + protected clear() { if (this.intervalId) { clearInterval(this.intervalId); delete this.intervalId; @@ -141,7 +159,7 @@ export default class PollingSubscription implements Subscription { /** What happens when browser goes offline */ protected offlineListener = () => { // this clears existing listeners, so no need to clear offline listener - this.cleanup(); + this.clear(); this.connectionListener.addOnlineListener(this.onlineListener); }; @@ -171,7 +189,7 @@ export default class PollingSubscription implements Subscription { * Will clean up old poll interval on next run */ protected run() { - if (this.startId) return; + if (this.startId || this.stopped) return; if (this.intervalId) this.lastIntervalId = this.intervalId; this.intervalId = setInterval(() => { // since we don't know how long into the last poll it was before resetting diff --git a/packages/core/src/manager/SubscriptionManager.ts b/packages/core/src/manager/SubscriptionManager.ts index d9e6ac4811d9..72fb7d7ab307 100644 --- a/packages/core/src/manager/SubscriptionManager.ts +++ b/packages/core/src/manager/SubscriptionManager.ts @@ -13,7 +13,10 @@ type Actions = UnsubscribeAction | SubscribeAction; export interface Subscription { add(frequency?: number): void; remove(frequency?: number): boolean; + /** Stops background work, like timers. `init()` may resume it. */ cleanup(): void; + /** Resumes background work stopped by `cleanup()`. Does nothing while already running. */ + init?(): void; } /** The static class that constructs Subscription */ @@ -40,14 +43,26 @@ export default class SubscriptionManager< declare protected readonly Subscription: S; protected controller: Controller = new Controller(); + /** Between `cleanup()` and `init()`: subscriptions are tracked but do not run. */ + protected paused = false; constructor(Subscription: S) { this.Subscription = Subscription; } middleware: Middleware = controller => { + // Managers shared by a remounted DataProvider: subscriptions from the old store + // would keep fetching for it, so drop them + if (controller !== this.controller) { + for (const key in this.subscriptions) { + this.subscriptions[key].cleanup(); + } + this.subscriptions = {}; + } this.controller = controller; return next => action => { + // the old store's actions must not touch the new store's subscriptions + if (controller !== this.controller) return next(action); switch (action.type) { case SUBSCRIBE: try { @@ -65,8 +80,17 @@ export default class SubscriptionManager< }; }; - /** Ensures all subscriptions are cleaned up. */ + /** Resumes every subscription stopped by `cleanup()`. */ + init() { + this.paused = false; + for (const key in this.subscriptions) { + this.subscriptions[key].init?.(); + } + } + + /** Pauses every subscription. They stay tracked, so `init()` resumes them. */ cleanup() { + this.paused = true; for (const key in this.subscriptions) { this.subscriptions[key].cleanup(); } @@ -82,10 +106,14 @@ export default class SubscriptionManager< const frequency = action.endpoint.pollFrequency; this.subscriptions[key].add(frequency); } else { - this.subscriptions[key] = new this.Subscription( + const subscription = new this.Subscription( action, this.controller, ) as InstanceType; + // a subscription starts in its constructor; while paused it waits for init(). + // One without init() could never resume, so it keeps running. + if (this.paused && subscription.init) subscription.cleanup(); + this.subscriptions[key] = subscription; } } diff --git a/packages/core/src/manager/__tests__/devtoolsManager.ts b/packages/core/src/manager/__tests__/devtoolsManager.ts index 86b9f668f498..9ecb7647e7f0 100644 --- a/packages/core/src/manager/__tests__/devtoolsManager.ts +++ b/packages/core/src/manager/__tests__/devtoolsManager.ts @@ -311,15 +311,40 @@ describe('DevToolsManager', () => { expect(actionLogs().get('App')).toHaveLength(4); }); - it('forgets polling keys on cleanup', () => { + it('keeps capping a polling key after cleanup() and init()', () => { const { manager, dispatch } = pollingSetup(); dispatch(subscribe('a')); + // SubscriptionManager.init() resumes the poll without a new SUBSCRIBE manager.cleanup(); manager.init(initialState); for (let i = 1; i <= 3; i++) dispatch(fetchAction('a', i)); + expect(typesAndKeys().filter(([type]) => type === FETCH)).toHaveLength(2); + }); + + it('forgets polling keys when bound to a new store', () => { + const { manager, dispatch } = pollingSetup(); + dispatch(subscribe('a')); + manager.cleanup(); + const { dispatch: newDispatch } = setup(manager); + manager.init(initialState); + for (let i = 1; i <= 3; i++) newDispatch(fetchAction('a', i)); expect(typesAndKeys().filter(([type]) => type === FETCH)).toHaveLength(3); }); + it('ignores actions from a previous store', () => { + const { manager, dispatch: oldDispatch } = pollingSetup(); + manager.cleanup(); + const { dispatch } = setup(manager); + manager.init(initialState); + oldDispatch(subscribe('a')); + for (let i = 1; i <= 3; i++) dispatch(fetchAction('a', i)); + expect(typesAndKeys()).toEqual([ + [FETCH, 'a'], + [FETCH, 'a'], + [FETCH, 'a'], + ]); + }); + it('does not cap subscriptions without pollFrequency', () => { const { dispatch } = pollingSetup(); dispatch({ ...subscribe('a'), endpoint: { name: 'live' } }); diff --git a/packages/core/src/manager/__tests__/pollingSubscription.ts b/packages/core/src/manager/__tests__/pollingSubscription.ts index 5ac218511328..0a04bc2e82da 100644 --- a/packages/core/src/manager/__tests__/pollingSubscription.ts +++ b/packages/core/src/manager/__tests__/pollingSubscription.ts @@ -454,3 +454,84 @@ describe('PollingSubscription', () => { }); }); }); + +describe('PollingSubscription init() after cleanup()', () => { + beforeEach(() => { + jest.useFakeTimers(); + }); + afterEach(() => { + jest.useRealTimers(); + }); + + function create(online = true) { + const dispatch = jest.fn(() => Promise.resolve()); + const endpoint = new Endpoint(() => Promise.resolve({ id: 5 }), { + schema: Article, + key: () => 'test.com', + pollFrequency: 5000, + }); + const controller = new Controller({ dispatch }); + (controller as any).getState = makeState('test.com', 0); + const listener = new MockConnectionListener(online); + const sub = new PollingSubscription( + createSubscription(endpoint, { args: [] }), + controller, + listener, + ); + jest.advanceTimersByTime(1); + return { dispatch, sub, listener }; + } + + it('resumes polling', () => { + const { dispatch, sub } = create(); + sub.cleanup(); + dispatch.mockClear(); + jest.advanceTimersByTime(20000); + expect(dispatch).not.toHaveBeenCalled(); + + sub.init(); + jest.advanceTimersByTime(1); + expect(dispatch).toHaveBeenCalledTimes(1); + jest.advanceTimersByTime(10000); + expect(dispatch).toHaveBeenCalledTimes(3); + sub.cleanup(); + }); + + it('does nothing while already running', () => { + const { dispatch, sub } = create(); + dispatch.mockClear(); + sub.init(); + jest.advanceTimersByTime(10000); + expect(dispatch).toHaveBeenCalledTimes(2); + sub.cleanup(); + }); + + it('does not start when a faster frequency is added while stopped', () => { + const { dispatch, sub } = create(); + sub.cleanup(); + dispatch.mockClear(); + sub.add(1000); + jest.advanceTimersByTime(10000); + expect(dispatch).not.toHaveBeenCalled(); + + sub.init(); + jest.advanceTimersByTime(3001); + expect(dispatch).toHaveBeenCalledTimes(4); + sub.cleanup(); + }); + + it('waits to come online when resumed offline', () => { + const { dispatch, sub, listener } = create(); + sub.cleanup(); + listener.online = false; + dispatch.mockClear(); + sub.init(); + jest.advanceTimersByTime(20000); + expect(dispatch).not.toHaveBeenCalled(); + + listener.trigger('online'); + jest.advanceTimersByTime(1); + expect(dispatch).toHaveBeenCalledTimes(1); + sub.cleanup(); + }); +}); diff --git a/packages/core/src/manager/__tests__/subscriptionManager.ts b/packages/core/src/manager/__tests__/subscriptionManager.ts index 1aa0afa253fd..2b4ad0caf971 100644 --- a/packages/core/src/manager/__tests__/subscriptionManager.ts +++ b/packages/core/src/manager/__tests__/subscriptionManager.ts @@ -23,6 +23,7 @@ describe('SubscriptionManager', () => { add = jest.fn(); remove = jest.fn(() => true); cleanup = jest.fn(); + init = jest.fn(); } const manager = new SubscriptionManager(TestSubscription); const getState = () => initialState; @@ -45,6 +46,109 @@ describe('SubscriptionManager', () => { }); }); + describe('init()', () => { + it('resumes every tracked Subscription', () => { + const manager = new SubscriptionManager(TestSubscription); + const sub = new TestSubscription(); + (manager as any).subscriptions[ + PollingArticleResource.get.key({ id: 5 }) + ] = sub; + manager.cleanup(); + manager.init(); + expect(sub.init).toHaveBeenCalledTimes(1); + }); + + it('stops a Subscription created while paused until init()', () => { + const manager = new SubscriptionManager(TestSubscription); + const next = manager.middleware(new Controller())(() => + Promise.resolve(), + ); + manager.cleanup(); + next({ + type: SUBSCRIBE, + endpoint: PollingArticleResource.get, + args: [{ id: 5 }], + key: PollingArticleResource.get.key({ id: 5 }), + } as SubscribeAction); + const sub: TestSubscription = (manager as any).subscriptions[ + PollingArticleResource.get.key({ id: 5 }) + ]; + expect(sub.cleanup).toHaveBeenCalledTimes(1); + manager.init(); + expect(sub.init).toHaveBeenCalledTimes(1); + }); + + it('drops subscriptions from a previous store when bound to a new one', () => { + const manager = new SubscriptionManager(TestSubscription); + const action = { + type: SUBSCRIBE, + endpoint: PollingArticleResource.get, + args: [{ id: 5 }], + key: PollingArticleResource.get.key({ id: 5 }), + } as SubscribeAction; + manager.middleware(new Controller())(() => Promise.resolve())(action); + const old: TestSubscription = (manager as any).subscriptions[action.key]; + manager.cleanup(); + + manager.middleware(new Controller())(() => Promise.resolve())(action); + manager.init(); + const current: TestSubscription = (manager as any).subscriptions[ + action.key + ]; + expect(current).not.toBe(old); + expect(old.add).not.toHaveBeenCalled(); + expect(old.init).not.toHaveBeenCalled(); + expect(current.init).toHaveBeenCalledTimes(1); + }); + + it('ignores actions from a previous store', () => { + const manager = new SubscriptionManager(TestSubscription); + const action = { + type: SUBSCRIBE, + endpoint: PollingArticleResource.get, + args: [{ id: 5 }], + key: PollingArticleResource.get.key({ id: 5 }), + } as SubscribeAction; + const oldNext = manager.middleware(new Controller())(() => + Promise.resolve(), + ); + oldNext(action); + manager.middleware(new Controller())(() => Promise.resolve())(action); + const current: TestSubscription = (manager as any).subscriptions[ + action.key + ]; + + oldNext({ ...action, type: UNSUBSCRIBE } as UnsubscribeAction); + expect(current.remove).not.toHaveBeenCalled(); + expect((manager as any).subscriptions[action.key]).toBe(current); + }); + + it('keeps a Subscription without init() created while paused running', () => { + class NoInitSubscription implements Subscription { + add = jest.fn(); + remove = jest.fn(() => true); + cleanup = jest.fn(); + } + const manager = new SubscriptionManager(NoInitSubscription); + const next = manager.middleware(new Controller())(() => + Promise.resolve(), + ); + manager.cleanup(); + next({ + type: SUBSCRIBE, + endpoint: PollingArticleResource.get, + args: [{ id: 5 }], + key: PollingArticleResource.get.key({ id: 5 }), + } as SubscribeAction); + const sub: NoInitSubscription = (manager as any).subscriptions[ + PollingArticleResource.get.key({ id: 5 }) + ]; + expect(sub.cleanup).not.toHaveBeenCalled(); + manager.init(); + expect(sub.cleanup).not.toHaveBeenCalled(); + }); + }); + describe('middleware', () => { function createSubscribeAction( response: Record, diff --git a/packages/react/src/components/__tests__/activity.tsx b/packages/react/src/components/__tests__/activity.tsx index e1a86a7b8d12..8e2a6b0eb27b 100644 --- a/packages/react/src/components/__tests__/activity.tsx +++ b/packages/react/src/components/__tests__/activity.tsx @@ -198,6 +198,32 @@ describeIfActivity(' above ', () => { await wait(60); expect(calls).toBeGreaterThan(hiddenAt); }); + + it('resumes polling from controller.subscribe() after showing', async () => { + let calls = 0; + const endpoint = CoolerArticleResource.get.extend({ + pollFrequency: 20, + fetch() { + calls++; + return Promise.resolve({ id: 5, title: `poll ${calls}`, content: 'x' }); + }, + }); + const { hide, show } = renderTabs(); + // no component unsubscribes this, so it outlives the hide + await act(() => ctrl.subscribe(endpoint, { id: 5 })); + await wait(50); + expect(calls).toBeGreaterThan(0); + + await hide(); + const hiddenAt = calls; + await wait(60); + expect(calls).toBe(hiddenAt); + + await show(); + await wait(60); + expect(calls).toBeGreaterThan(hiddenAt); + await act(() => ctrl.unsubscribe(endpoint, { id: 5 })); + }); }); describe(' remounted with the same managers', () => { @@ -272,6 +298,30 @@ describe(' remounted with the same managers', () => { expect(container.textContent).toBe('new'); }); + it('polls for the new store after controller.subscribe() outlived the old one', async () => { + let calls = 0; + const endpoint = CoolerArticleResource.get.extend({ + pollFrequency: 20, + fetch() { + calls++; + return Promise.resolve({ id: 5, title: 'poll', content: 'x' }); + }, + }); + const mount = renderWithSharedManagers(endpoint); + const first = mount(); + // never unsubscribed, so it outlives the unmount + await act(() => ctrl.subscribe(endpoint, { id: 5 })); + first.unmount(); + + mount(); + await act(() => ctrl.subscribe(endpoint, { id: 5 })); + const subscribedAt = calls; + await wait(60); + // the unmounted store's fetches are never sent, so these come from the new store + expect(calls).toBeGreaterThan(subscribedAt); + await act(() => ctrl.unsubscribe(endpoint, { id: 5 })); + }); + it('settles fetches in StrictMode, where render and Effects run twice', async () => { const get = deferred(CoolerArticleResource.get); const mount = renderWithSharedManagers(get.endpoint, StrictMode); diff --git a/website/blog/2026-11-18-v0.19-batch-set.md b/website/blog/2026-11-18-v0.19-batch-set.md index bf166ab095f8..4fa78b56cc01 100644 --- a/website/blog/2026-11-18-v0.19-batch-set.md +++ b/website/blog/2026-11-18-v0.19-batch-set.md @@ -464,6 +464,7 @@ To show something specific when the refetch failed (for example a 404 after dele - `react` [Controller.fetch()](/docs/api/Controller#fetch) of an endpoint without `sideEffect` never rejects unhandled, so a read you don't await needs no `.catch()`: components reading that endpoint show its stored error. Mutations still reject. This also stops React Native's unhandled rejection warning when a refetch on screen focus fails. [Upgrade notes](#fetch-read-prehandled) ([#4670](https://github.com/reactive/data-client/pull/4670)) - `react` Support React [``](https://react.dev/reference/react/Activity) above [DataProvider](/docs/api/DataProvider). Before, hiding `DataProvider` dropped responses, fetches and subscriptions, which left [useSuspense()](/docs/api/useSuspense) loading forever. Most apps should still put `DataProvider` at the root, above ``, which works as before. A response to a fetch started before [resetEntireStore()](/docs/api/Controller#resetEntireStore) is always dropped, so custom managers should pass the fetch's own `fetchedAt` to [controller.resolve()](/docs/api/Controller#resolve); the v0.19 codemod does this where a Manager resolves `action.endpoint` under an `actionTypes.FETCH` check ([#4593](https://github.com/reactive/data-client/pull/4593)) +- `react` `vue` **Fix:** Polling from [controller.subscribe()](/docs/api/Controller#subscribe) resumes after `` shows a hidden `DataProvider`, and a custom [Subscription](/docs/api/SubscriptionManager#subscription) can resume in `init()` ([#4639](https://github.com/reactive/data-client/pull/4639)) - `react` `vue` **Fix:** [useLoading()](/docs/api/useLoading) clears `error` when the wrapped function is called again, so a form no longer shows an old error after a later submit succeeds. When calls overlap, React and Vue `loading` and `error` follow the latest call, and a call that settles inside a hidden `` shows its result once visible ([#4614](https://github.com/reactive/data-client/pull/4614)) - `react` `vue` **Fix:** A cached result no longer keeps showing a nested entity as missing after that entity was `INVALID` or `null` and becomes valid again ([#4460](https://github.com/reactive/data-client/pull/4460)) - `react` **Fix:** [useCancelling()](/docs/api/useCancelling) no longer aborts the request its own component is waiting on when it re-renders while suspended, which could leave slow requests loading forever ([#4516](https://github.com/reactive/data-client/pull/4516)) diff --git a/website/src/components/Playground/editor-types/@data-client/core.d.ts b/website/src/components/Playground/editor-types/@data-client/core.d.ts index 0445a0de242e..ec37d9da064a 100644 --- a/website/src/components/Playground/editor-types/@data-client/core.d.ts +++ b/website/src/components/Playground/editor-types/@data-client/core.d.ts @@ -1315,7 +1315,10 @@ type Actions = UnsubscribeAction | SubscribeAction; interface Subscription { add(frequency?: number): void; remove(frequency?: number): boolean; + /** Stops background work, like timers. `init()` may resume it. */ cleanup(): void; + /** Resumes background work stopped by `cleanup()`. Does nothing while already running. */ + init?(): void; } /** The static class that constructs Subscription */ interface SubscriptionConstructable { @@ -1334,9 +1337,13 @@ declare class SubscriptionManager; protected startId?: ReturnType; private connectionListener; + /** Stopped by `cleanup()` until `init()` */ + private stopped; constructor(action: Omit, controller: Controller, connectionListener?: ConnectionListener); + /** Resumes polling stopped by `cleanup()` */ + init(): void; + protected start(): void; /** Subscribe to a frequency */ add(frequency?: number): void; /** Unsubscribe from a frequency */ remove(frequency?: number): boolean; - /** Cleanup means clearing out background interval. */ + /** Cleanup means clearing out background interval. `init()` resumes it. */ cleanup(): void; + protected clear(): void; /** Trigger request for latest resource */ protected update(): void; /** What happens when browser goes offline */