/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.elasticsearch.indices.fielddata.cache;

import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.index.fielddata.AtomicFieldData;
import org.elasticsearch.index.fielddata.FieldDataType;
import org.elasticsearch.index.fielddata.IndexFieldDataCache;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.indices.fielddata.breaker.CircuitBreakerService;

/**
 * A {@link IndexFieldDataCache.Listener} implementation that updates indices (node) level statistics / service about
 * field data entries being loaded and unloaded.
 *
 * Currently it only decrements the memory used in the  {@link CircuitBreakerService}.
 */
public class IndicesFieldDataCacheListener implements IndexFieldDataCache.Listener {

    private final CircuitBreakerService circuitBreakerService;

    @Inject
    public IndicesFieldDataCacheListener(CircuitBreakerService circuitBreakerService) {
        this.circuitBreakerService = circuitBreakerService;
    }

    @Override
    public void onLoad(FieldMapper.Names fieldNames, FieldDataType fieldDataType, AtomicFieldData fieldData) {
    }

    @Override
    public void onUnload(FieldMapper.Names fieldNames, FieldDataType fieldDataType, boolean wasEvicted, long sizeInBytes, @Nullable AtomicFieldData fieldData) {
        assert sizeInBytes > 0 : "When reducing circuit breaker, it should be adjusted with a positive number and not [" + sizeInBytes + "]";
        circuitBreakerService.getBreaker().addWithoutBreaking(-sizeInBytes);
    }

}

@@ -2143,16 +2143,17 @@
 nBytes %3E
+=
  0 : %22Wh
@@ -2214,23 +2214,35 @@
 h a 
-positive number
+number higher or equal to 0
  and

sizeInBytes can be 0