Skip to content

Commit

Permalink
Don't set up more than 1 abort signal listener (#503)
Browse files Browse the repository at this point in the history
  • Loading branch information
gustavohenke authored Sep 12, 2024
1 parent a7a5894 commit 041520b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
11 changes: 11 additions & 0 deletions src/completion-listener.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { getEventListeners, getMaxListeners } from 'events';
import { TestScheduler } from 'rxjs/testing';

import { CloseEvent } from './command';
Expand Down Expand Up @@ -56,6 +57,16 @@ describe('listen', () => {
await expect(result).resolves.toHaveLength(0);
});

it('does not leak memory when listening for abort signals', () => {
const abortCtrl = new AbortController();
const maxListeners = getMaxListeners(abortCtrl.signal);
createController().listen(
Array.from({ length: maxListeners + 1 }, () => new FakeCommand()),
abortCtrl.signal,
);
expect(getEventListeners(abortCtrl.signal, 'abort')).toHaveLength(1);
});

it('check for success once all commands have emitted at least a single close event', async () => {
const finallyCallback = jest.fn();
const result = createController().listen(commands).finally(finallyCallback);
Expand Down
5 changes: 4 additions & 1 deletion src/completion-listener.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as Rx from 'rxjs';
import { delay, filter, map, switchMap, take } from 'rxjs/operators';
import { delay, filter, map, share, switchMap, take } from 'rxjs/operators';

import { CloseEvent, Command } from './command';

Expand Down Expand Up @@ -101,6 +101,9 @@ export class CompletionListener {
// without an immediate delay
delay(0, this.scheduler),
map(() => undefined),
// #502 - node might warn of too many active listeners on this object if it isn't shared,
// as each command subscribes to abort event over and over
share(),
);

const closeStreams = commands.map((command) =>
Expand Down

0 comments on commit 041520b

Please sign in to comment.