@@ -75,9 +75,19 @@ export async function createEnvironmentFixture(
7575 let projectSettingAdded = false ;
7676 let environmentCreated = false ;
7777 let environment : PythonEnvironment | undefined ;
78+ let apiRemovalSettled = false ;
7879 let disposePromise : Promise < void > | undefined ;
7980 let markerWritten = false ;
8081 let projectRootCreated = false ;
82+ const getApiRemoval = createSingleFlightOperation ( ( ) => {
83+ if ( ! environment ) {
84+ return Promise . resolve ( ) ;
85+ }
86+ apiRemovalSettled = false ;
87+ return api . removeEnvironment ( environment , { runHeadless : true } ) . finally ( ( ) => {
88+ apiRemovalSettled = true ;
89+ } ) ;
90+ } ) ;
8191
8292 const cleanup = async ( ) : Promise < void > => {
8393 const cleanupErrors : Error [ ] = [ ] ;
@@ -92,15 +102,10 @@ export async function createEnvironmentFixture(
92102 cleanupErrors . push ( toError ( error ) ) ;
93103 }
94104 if ( ownershipVerified && environment ) {
95- let apiRemovalSettled = false ;
96- const apiRemoval = api
97- . removeEnvironment ( environment , { runHeadless : true } )
98- . finally ( ( ) => {
99- apiRemovalSettled = true ;
100- } ) ;
105+ const apiRemovalPromise = getApiRemoval ( ) ;
101106 try {
102107 await withTimeout (
103- apiRemoval ,
108+ apiRemovalPromise ,
104109 COMMAND_TIMEOUT_MS ,
105110 `${ request . name } API environment removal timed out` ,
106111 ) ;
@@ -109,7 +114,7 @@ export async function createEnvironmentFixture(
109114 if ( ! apiRemovalSettled ) {
110115 try {
111116 await withTimeout (
112- apiRemoval ,
117+ apiRemovalPromise ,
113118 API_REMOVAL_SETTLE_TIMEOUT_MS ,
114119 `${ request . name } API environment removal did not settle after timing out` ,
115120 ) ;
@@ -537,6 +542,17 @@ async function withTimeout<T>(operation: Promise<T>, timeoutMs: number, message:
537542 }
538543}
539544
545+ /**
546+ * Returns a function that starts an asynchronous operation at most once and shares its promise.
547+ */
548+ export function createSingleFlightOperation < T > ( operation : ( ) => Promise < T > ) : ( ) => Promise < T > {
549+ let promise : Promise < T > | undefined ;
550+ return ( ) => {
551+ promise ??= operation ( ) ;
552+ return promise ;
553+ } ;
554+ }
555+
540556function sanitizeName ( value : string ) : string {
541557 return value . toLowerCase ( ) . replace ( / [ ^ a - z 0 - 9 - ] / g, '-' ) ;
542558}
0 commit comments