/*
 * 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.
 */

package org.apache.polaris.service.tracing;

import io.smallrye.mutiny.Uni;
import jakarta.annotation.Nonnull;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.ws.rs.container.ContainerRequestContext;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Default implementation of {@link RequestIdGenerator}, striking a balance between randomness and
 * performance.
 *
 * <p>The IDs generated by this generator are of the form: {@code UUID_COUNTER}. The UUID part is
 * randomly generated at startup, and the counter is incremented for each request.
 *
 * <p>In the unlikely event that the counter overflows, a new UUID is generated and the counter is
 * reset to 1.
 */
@ApplicationScoped
public class DefaultRequestIdGenerator implements RequestIdGenerator {

  record RequestId(UUID uuid, long counter) {

    RequestId() {
      this(UUID.randomUUID(), 1);
    }

    @Override
    @Nonnull
    public String toString() {
      return String.format("%s_%019d", uuid(), counter());
    }

    RequestId increment() {
      return counter == Long.MAX_VALUE ? new RequestId() : new RequestId(uuid, counter + 1);
    }
  }

  final AtomicReference<RequestId> state = new AtomicReference<>(new RequestId());

  @Override
  public Uni<String> generateRequestId(ContainerRequestContext requestContext) {
    return Uni.createFrom().item(nextRequestId().toString());
  }

  RequestId nextRequestId() {
    return state.getAndUpdate(RequestId::increment);
  }
}
