@@ -568,17 +568,16 @@ func resourceVirtualIndexCreate(ctx context.Context, d *schema.ResourceData, m i
568568
569569 primaryIndexName := d .Get ("primary_index_name" ).(string )
570570 primaryIndex := apiClient .searchClient .InitIndex (primaryIndexName )
571+
572+ // Modifying the primary's replica setting on primary can cause problems if other replicas
573+ // are modifying it at the same time. Lock the primary until we're done in order to prevent that.
574+ mutexKV .Lock (ctx , algoliaIndexMutexKey (apiClient .appID , primaryIndexName ))
571575 primaryIndexSettings , err := primaryIndex .GetSettings (ctx )
572576 if err != nil {
573577 return diag .FromErr (err )
574578 }
575-
576579 replicas := primaryIndexSettings .Replicas .Get ()
577580 if ! algoliautil .IndexExistsInReplicas (replicas , indexName , true ) {
578- // Modifying the primary's replica setting on primary can cause problems if other replicas
579- // are modifying it at the same time. Lock the primary until we're done in order to prevent that.
580- mutexKV .Lock (ctx , algoliaIndexMutexKey (apiClient .appID , primaryIndexName ))
581- defer mutexKV .Unlock (ctx , algoliaIndexMutexKey (apiClient .appID , primaryIndexName ))
582581
583582 newReplicas := append (primaryIndexSettings .Replicas .Get (), fmt .Sprintf ("virtual(%s)" , indexName ))
584583 res , err := primaryIndex .SetSettings (search.Settings {
@@ -591,6 +590,7 @@ func resourceVirtualIndexCreate(ctx context.Context, d *schema.ResourceData, m i
591590 return diag .FromErr (err )
592591 }
593592 }
593+ mutexKV .Unlock (ctx , algoliaIndexMutexKey (apiClient .appID , primaryIndexName ))
594594
595595 index := apiClient .searchClient .InitIndex (indexName )
596596 res , err := index .SetSettings (mapToVirtualIndexSettings (d ))
0 commit comments