From 34e504b65b3e3bb97cabfbc107421546bd82df21 Mon Sep 17 00:00:00 2001 From: Janne Savolainen Date: Thu, 5 May 2022 11:20:25 +0300 Subject: [PATCH] Prevent restarting a startableStoppable when already being started Co-authored-by: Mikko Aspiala Signed-off-by: Janne Savolainen --- .../utils/get-startable-stoppable.test.ts | 18 ++++++++++++++++++ src/common/utils/get-startable-stoppable.ts | 8 ++++++++ 2 files changed, 26 insertions(+) diff --git a/src/common/utils/get-startable-stoppable.test.ts b/src/common/utils/get-startable-stoppable.test.ts index dc692b3f0a..24b9e1862d 100644 --- a/src/common/utils/get-startable-stoppable.test.ts +++ b/src/common/utils/get-startable-stoppable.test.ts @@ -57,6 +57,24 @@ describe("getStartableStoppable", () => { expect(actual.started).toBe(false); }); + describe("when started again before the start has finished", () => { + let error: Error; + + beforeEach(() => { + startMock.mockClear(); + + actual.start().catch((e) => { error = e; }); + }); + + it("does not start starting again", () => { + expect(startMock).not.toHaveBeenCalled(); + }); + + it("throws", () => { + expect(error.message).toBe("Tried to start \"some-id\", but it is already being started."); + }); + }); + describe("when starting finishes", () => { beforeEach(async () => { await startMock.resolve(stopMock); diff --git a/src/common/utils/get-startable-stoppable.ts b/src/common/utils/get-startable-stoppable.ts index 59f7964d97..5590157ab8 100644 --- a/src/common/utils/get-startable-stoppable.ts +++ b/src/common/utils/get-startable-stoppable.ts @@ -13,6 +13,7 @@ export const getStartableStoppable = ( let stop: Stopper; let stopped = false; let started = false; + let starting = false; let startingPromise: Promise | Stopper; return { @@ -21,6 +22,12 @@ export const getStartableStoppable = ( }, start: async () => { + if (starting) { + throw new Error(`Tried to start "${id}", but it is already being started.`); + } + + starting = true; + if (started) { throw new Error(`Tried to start "${id}", but it has already started.`); } @@ -30,6 +37,7 @@ export const getStartableStoppable = ( stopped = false; started = true; + starting = false; }, stop: async () => {