/*
 * Licensed 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 io.trino.tracing;

import com.google.errorprone.annotations.MustBeClosed;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Scope;

import static java.util.Objects.requireNonNull;

public final class ScopedSpan
        implements AutoCloseable
{
    private final Span span;
    private final Scope scope;

    @SuppressWarnings("MustBeClosedChecker")
    private ScopedSpan(Span span)
    {
        this.span = requireNonNull(span, "span is null");
        this.scope = span.makeCurrent();
    }

    @Override
    public void close()
    {
        try {
            scope.close();
        }
        finally {
            span.end();
        }
    }

    @MustBeClosed
    public static ScopedSpan scopedSpan(Tracer tracer, String name)
    {
        return scopedSpan(tracer.spanBuilder(name).startSpan());
    }

    @MustBeClosed
    public static ScopedSpan scopedSpan(Span span)
    {
        return new ScopedSpan(span);
    }
}
