# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF 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.

rules:
  - name: envoy-als
    dsl: |
      filter {
        // only collect abnormal logs (http status code >= 300, or commonProperties?.responseFlags is not empty)
        if (parsed?.response?.responseCode?.value as Integer < 400 && !parsed?.commonProperties?.responseFlags?.toString()?.trim()) {
          abort {}
        }
        extractor {
          if (parsed?.response?.responseCode) {
            tag 'status.code': parsed?.response?.responseCode?.value
          }
          tag 'response.flag': parsed?.commonProperties?.responseFlags
        }
        sink {
          sampler {
            if (parsed?.commonProperties?.responseFlags?.toString()) {
              // use service:errorCode as sampler id so that each service:errorCode has its own sampler,
              // e.g. checkoutservice:[upstreamConnectionFailure], checkoutservice:[upstreamRetryLimitExceeded]
              rateLimit("${log.service}:${parsed?.commonProperties?.responseFlags?.toString()}") {
                rpm 6000
              }
            } else {
              // use service:responseCode as sampler id so that each service:responseCode has its own sampler,
              // e.g. checkoutservice:500, checkoutservice:404.
              rateLimit("${log.service}:${parsed?.response?.responseCode}") {
                rpm 6000
              }
            }
          }
        }
      }
