001/*
002 * Copyright 2022-2026 Revetware LLC.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.soklet;
018
019import org.jspecify.annotations.NonNull;
020
021import javax.annotation.concurrent.ThreadSafe;
022import java.time.Duration;
023
024import static java.util.Objects.requireNonNull;
025
026/**
027 * Framework-created advisory phase and deadline information borrowed by a
028 * transport for one shutdown invocation. Soklet owns the context and its
029 * absolute phase boundary; a transport may inspect it but cannot extend the
030 * deadline.
031 *
032 * @author <a href="https://www.revetkn.com">Mark Allen</a>
033 */
034@ThreadSafe
035public final class ShutdownContext {
036        @NonNull
037        private final ShutdownPhase shutdownPhase;
038        @NonNull
039        private final NanoClock clock;
040        private final long absoluteDeadlineNanos;
041
042        ShutdownContext(@NonNull ShutdownPhase shutdownPhase,
043                        @NonNull NanoClock clock, long absoluteDeadlineNanos) {
044                this.shutdownPhase = requireNonNull(shutdownPhase);
045                this.clock = requireNonNull(clock);
046                this.absoluteDeadlineNanos = absoluteDeadlineNanos;
047        }
048
049        /**
050         * Acquires the current shutdown phase.
051         *
052         * @return the current shutdown phase
053         */
054        @NonNull
055        public ShutdownPhase getShutdownPhase() {
056                return this.shutdownPhase;
057        }
058
059        /**
060         * Acquires the time remaining before the current phase boundary.
061         *
062         * @return the remaining time, clamped to zero
063         */
064        @NonNull
065        public Duration getRemainingTime() {
066                return LifecycleDeadlines.remaining(this.absoluteDeadlineNanos,
067                                this.clock.nanoTime());
068        }
069
070        long absoluteDeadlineNanos() {
071                return this.absoluteDeadlineNanos;
072        }
073}