Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: pool.cancelPendingTasks method #53

Merged
merged 1 commit into from
Apr 13, 2023

Conversation

AriPerkkio
Copy link
Member

Here is the same test case with signal usage to demonstrate the issue clearly:

import EventEmitter from 'events'

test('queued tasks can be aborted', async () => {
  const pool = new Tinypool({
    filename: resolve(__dirname, 'fixtures/sleep.js'),
    minThreads: 0,
    maxThreads: 1,
  })

  const signal = new EventEmitter()

  const time = 500
  const promises = []
  let finishedTasks = 0
  let cancelledTasks = 0

  for (const _ of Array(10).fill(0)) {
    const promise = pool
      .run({ time }, { signal })
      .then(() => {
        finishedTasks++
      })
      .catch((error) => {
        if (error.message !== 'The task has been aborted') {
          throw error
        }
        cancelledTasks++
      })
    promises.push(promise)
  }

  // Wait for task to start
  await new Promise((resolve) => setTimeout(resolve, time / 2))
  expect(pool.queueSize).toBe(9)

  // One task is running, cancel the pending ones
  signal.emit('abort')

  // The first task should still be on-going, pending ones should be cancelled
  expect(finishedTasks).toBe(0)
  expect(pool.queueSize).toBe(0)

  await Promise.all(promises)

  expect({ finishedTasks, cancelledTasks }).toEqual({
    finishedTasks: 1,
    cancelledTasks: 9,
  })
})

@AriPerkkio AriPerkkio force-pushed the feat/cancel-pending-tasks branch 2 times, most recently from ea73d4b to 303d926 Compare April 12, 2023 08:57
@Aslemammad
Copy link
Member

Nice! Please try adding a documentation.

@AriPerkkio
Copy link
Member Author

Documentation added. I did some refactoring to the old ones to make sure constructor options, pool methods and package exports are in their own sections.

@Aslemammad
Copy link
Member

Thank you so much.

@Aslemammad Aslemammad merged commit 65c9b36 into tinylibs:main Apr 13, 2023
@AriPerkkio AriPerkkio deleted the feat/cancel-pending-tasks branch April 13, 2023 07:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Feature: pool.cancelPendingTasks method for gracefully cancelling all tasks that have not started
2 participants