Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions .changeset/subscription-resume.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
---
'@data-client/core': patch
'@data-client/react': patch
'@data-client/vue': patch
---

Fix polling from `controller.subscribe()` staying stopped after `<Activity>` hides `DataProvider`

When [`<Activity>`](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();
}
}
```
14 changes: 11 additions & 3 deletions docs/core/api/SubscriptionManager.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ interface Subscription {
add(frequency?: number): void;
remove(frequency?: number): boolean;
cleanup(): void;
init?(): void;
}

/** The static class that constructs Subscription */
Expand All @@ -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

Expand All @@ -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()`

:::
11 changes: 7 additions & 4 deletions packages/core/src/manager/DevtoolsManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
this.controller = controller;
const reducer = getExtension() && createReducer(controller as any);
let state = controller.getState();
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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;
Comment thread
ntucker marked this conversation as resolved.
Resolved
const registry: DebugStore['registry'] | undefined = (globalThis as any)
.__DC__?.registry;
Expand Down
24 changes: 21 additions & 3 deletions packages/core/src/manager/PollingSubscription.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ export default class PollingSubscription implements Subscription {
declare protected lastIntervalId?: ReturnType<typeof setInterval>;
declare protected startId?: ReturnType<typeof setTimeout>;
declare private connectionListener: ConnectionListener;
/** Stopped by `cleanup()` until `init()` */
private stopped = false;

constructor(
action: Omit<SubscribeAction, 'type'>,
Expand All @@ -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 {
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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);
};

Expand Down Expand Up @@ -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
Expand Down
32 changes: 30 additions & 2 deletions packages/core/src/manager/SubscriptionManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 */
Expand All @@ -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;
Comment thread
ntucker marked this conversation as resolved.
Resolved
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 {
Expand All @@ -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();
}
Expand All @@ -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<S>;
// 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;
}
}

Expand Down
27 changes: 26 additions & 1 deletion packages/core/src/manager/__tests__/devtoolsManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' } });
Expand Down
81 changes: 81 additions & 0 deletions packages/core/src/manager/__tests__/pollingSubscription.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
});
Loading
Loading