@@ -2,6 +2,7 @@ package provider
22
33import (
44 "context"
5+ "fmt"
56 "log"
67 "strconv"
78 "time"
@@ -583,8 +584,14 @@ func resourceIndexCreate(ctx context.Context, d *schema.ResourceData, m interfac
583584
584585 indexName := d .Get ("name" ).(string )
585586
586- if primaryIndexName , ok := d .GetOk ("primary_index_name" ); ok {
587- primaryIndex := apiClient .searchClient .InitIndex (primaryIndexName .(string ))
587+ if v , ok := d .GetOk ("primary_index_name" ); ok {
588+ primaryIndexName := v .(string )
589+ // Modifying the primary's replica setting on primary can cause problems if other replicas
590+ // are modifying it at the same time. Lock the primary until we're done in order to prevent that.
591+ mutexKV .Lock (algoliaIndexMutexKey (apiClient .appID , primaryIndexName ))
592+ defer mutexKV .Unlock (algoliaIndexMutexKey (apiClient .appID , primaryIndexName ))
593+
594+ primaryIndex := apiClient .searchClient .InitIndex (primaryIndexName )
588595 primaryIndexSettings , err := primaryIndex .GetSettings (ctx )
589596 if err != nil {
590597 return diag .FromErr (err )
@@ -653,8 +660,14 @@ func resourceIndexDelete(ctx context.Context, d *schema.ResourceData, m interfac
653660 apiClient := m .(* apiClient )
654661 indexName := d .Id ()
655662
656- if primaryIndexName , ok := d .GetOk ("primary_index_name" ); ok {
657- primaryIndex := apiClient .searchClient .InitIndex (primaryIndexName .(string ))
663+ if v , ok := d .GetOk ("primary_index_name" ); ok {
664+ primaryIndexName := v .(string )
665+ // Modifying the primary's replica setting on primary can cause problems if other replicas
666+ // are modifying it at the same time. Lock the primary until we're done in order to prevent that.
667+ mutexKV .Lock (algoliaIndexMutexKey (apiClient .appID , primaryIndexName ))
668+ defer mutexKV .Unlock (algoliaIndexMutexKey (apiClient .appID , primaryIndexName ))
669+
670+ primaryIndex := apiClient .searchClient .InitIndex (primaryIndexName )
658671 primaryIndexSettings , err := primaryIndex .GetSettings (ctx )
659672 if err != nil {
660673 return diag .FromErr (err )
@@ -1224,3 +1237,7 @@ func unmarshalAdvancedConfig(configured interface{}, settings *search.Settings,
12241237 }
12251238 }
12261239}
1240+
1241+ func algoliaIndexMutexKey (appID string , indexName string ) string {
1242+ return fmt .Sprintf ("%s-algolia-index-%s" , appID , indexName )
1243+ }
0 commit comments