@@ -81,6 +81,10 @@ public static void putPolicy(
8181 }
8282
8383 updateClusterState (clusterService , handler , current -> {
84+ final Map <String , EnrichPolicy > originalPolicies = getPolicies (current );
85+ if (originalPolicies .containsKey (name )) {
86+ throw new ResourceAlreadyExistsException ("policy [{}] already exists" , name );
87+ }
8488 for (String indexExpression : policy .getIndices ()) {
8589 // indices field in policy can contain wildcards, aliases etc.
8690 String [] concreteIndices = indexNameExpressionResolver .concreteIndexNames (
@@ -101,12 +105,9 @@ public static void putPolicy(
101105 }
102106 }
103107
104- final Map <String , EnrichPolicy > policies = getPolicies (current );
105- EnrichPolicy existing = policies .putIfAbsent (name , policy );
106- if (existing != null ) {
107- throw new ResourceAlreadyExistsException ("policy [{}] already exists" , name );
108- }
109- return policies ;
108+ final Map <String , EnrichPolicy > updatedPolicies = new HashMap <>(originalPolicies );
109+ updatedPolicies .put (name , policy );
110+ return updatedPolicies ;
110111 });
111112 }
112113
@@ -125,13 +126,14 @@ public static void deletePolicy(String name, ClusterService clusterService, Cons
125126 }
126127
127128 updateClusterState (clusterService , handler , current -> {
128- final Map <String , EnrichPolicy > policies = getPolicies (current );
129- if (policies .containsKey (name ) == false ) {
129+ final Map <String , EnrichPolicy > originalPolicies = getPolicies (current );
130+ if (originalPolicies .containsKey (name ) == false ) {
130131 throw new ResourceNotFoundException ("policy [{}] not found" , name );
131132 }
132133
133- policies .remove (name );
134- return policies ;
134+ final Map <String , EnrichPolicy > updatedPolicies = new HashMap <>(originalPolicies );
135+ updatedPolicies .remove (name );
136+ return updatedPolicies ;
135137 });
136138 }
137139
@@ -153,18 +155,11 @@ public static EnrichPolicy getPolicy(String name, ClusterState state) {
153155 * Gets all policies in the cluster.
154156 *
155157 * @param state the cluster state
156- * @return a Map of <code>policyName, EnrichPolicy</code> of the policies
158+ * @return a read-only Map of <code>policyName, EnrichPolicy</code> of the policies
157159 */
158160 public static Map <String , EnrichPolicy > getPolicies (ClusterState state ) {
159- final Map <String , EnrichPolicy > policies ;
160- final EnrichMetadata enrichMetadata = state .metadata ().custom (EnrichMetadata .TYPE );
161- if (enrichMetadata != null ) {
162- // Make a copy, because policies map inside custom metadata is read only:
163- policies = new HashMap <>(enrichMetadata .getPolicies ());
164- } else {
165- policies = new HashMap <>();
166- }
167- return policies ;
161+ final EnrichMetadata metadata = state .metadata ().custom (EnrichMetadata .TYPE , EnrichMetadata .EMPTY );
162+ return metadata .getPolicies ();
168163 }
169164
170165 private static void updateClusterState (
0 commit comments