001/*
002 * Copyright 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.revetsec;
018
019import org.jspecify.annotations.NonNull;
020import org.jspecify.annotations.Nullable;
021
022import javax.annotation.concurrent.NotThreadSafe;
023import java.io.IOException;
024
025import static java.util.Objects.requireNonNull;
026
027/**
028 * The root of every exception Revetsec throws for a condition that a remote party, the input or the runtime
029 * environment can cause.
030 * <p>
031 * Programmer misuse, such as a {@code null} argument or an out-of-range setting, throws
032 * {@link NullPointerException}, {@link IllegalArgumentException} or {@link IllegalStateException} instead.
033 * <p>
034 * Every instance has:
035 * <ul>
036 *   <li>an {@link ErrorCategory} ({@link #getCategory()});</li>
037 *   <li>a temporary condition flag ({@link #isTemporaryCondition()}) set by the documented failure category,
038 *   reason, cause and response status. Only selected {@link ErrorCategory#TRANSPORT} conditions (timeout,
039 *   I/O failure or a held-back request) and {@link ErrorCategory#REMOTE_ERROR} responses (HTTP 429/5xx or OAuth
040 *   {@code temporarily_unavailable}) may be marked temporary. This is not an effect or replay verdict;</li>
041 *   <li>a fixed, one-sentence message that never contains input, tokens, keys or other secrets;</li>
042 *   <li>no cause, except the JDK {@link IOException} behind a {@link ErrorCategory#TRANSPORT} failure;</li>
043 *   <li>suppression disabled, so {@link #addSuppressed(Throwable)} does nothing and {@link #getSuppressed()} is
044 *   always empty.</li>
045 * </ul>
046 * The constructor is protected only so that Revetsec's own packages can extend this class. Applications catch
047 * Revetsec exceptions; they do not subclass or construct them, except through the factories a type documents for
048 * that purpose.
049 *
050 * @author <a href="https://www.revetkn.com">Mark Allen</a>
051 * @since 1.0.0
052 */
053@NotThreadSafe
054public abstract class RevetsecException extends RuntimeException {
055        /**
056         * The serialized form's version.
057         */
058        private static final long serialVersionUID = 1L;
059
060        /**
061         * The category of this failure; never {@code null}.
062         *
063         * @serial
064         */
065        private final ErrorCategory category;
066
067        /**
068         * Whether this failure is classified as a temporary condition; never {@code null}.
069         *
070         * @serial
071         */
072        private final Boolean transientFailure;
073
074        /**
075         * Creates an exception with a fixed message and suppression disabled.
076         * <p>
077         * The arguments must follow the rules in the class description: only {@link ErrorCategory#TRANSPORT} and
078         * {@link ErrorCategory#REMOTE_ERROR} failures may be transient, and only a {@link ErrorCategory#TRANSPORT}
079         * failure may carry a cause, which must be the JDK's {@link IOException}.
080         *
081         * @param category         the category of this failure
082         * @param transientFailure whether this failure is classified as a temporary condition
083         * @param fixedMessage     a fixed, non-blank, one-sentence message that contains no input and no secret
084         * @param cause            the JDK {@link IOException} behind a {@link ErrorCategory#TRANSPORT} failure, or
085         *                         {@code null}
086         * @throws NullPointerException     if {@code category}, {@code transientFailure} or {@code fixedMessage} is
087         *                                  {@code null}
088         * @throws IllegalArgumentException if the message is blank, a category other than {@code TRANSPORT} or
089         *                                  {@code REMOTE_ERROR} is marked transient, or a cause is given for a category
090         *                                  other than {@code TRANSPORT} or is not an {@link IOException}
091         * @since 1.0.0
092         */
093        protected RevetsecException(@NonNull ErrorCategory category,
094                                                                                                                        @NonNull Boolean transientFailure,
095                                                                                                                        @NonNull String fixedMessage,
096                                                                                                                        @Nullable Throwable cause) {
097                // Every check runs inside the super(...) arguments, before the object exists, so a failed construction
098                // never leaves a partially initialized instance behind (SpotBugs CT_CONSTRUCTOR_THROW).
099                super(checkedMessage(category, transientFailure, fixedMessage, cause), cause, false, true);
100                this.category = category;
101                this.transientFailure = transientFailure;
102        }
103
104        /**
105         * Returns the category of this failure.
106         *
107         * @return the category of this failure
108         * @since 1.0.0
109         */
110        @NonNull
111        public final ErrorCategory getCategory() {
112                return this.category;
113        }
114
115        /**
116         * Returns whether this failure is classified as a temporary condition.
117         * <p>
118         * It is {@code true} only for a {@link ErrorCategory#TRANSPORT} failure caused by a timeout or an I/O error, or
119         * by a request Revetsec held back so that it can be sent later, and for a {@link ErrorCategory#REMOTE_ERROR} with
120         * HTTP status 429 or 5xx or the OAuth error {@code temporarily_unavailable}. It is always {@code false} for an
121         * interrupted thread and for every other category.
122         * Documented fixed outcome reasons, including an unknown commit or a known commit whose output was withheld,
123         * retain their false classification even if a separately authorized later operation could succeed.
124         * <p>
125         * This classification supplies no permission to replay an operation. Neither value establishes whether a
126         * request was sent, whether earlier work had effects, whether a credential remains usable, or whether the
127         * operation is idempotent. A timeout, HTTP 429/5xx or OAuth {@code temporarily_unavailable} can follow remote
128         * consumption or commitment. A false value does not establish a permanent condition or zero effects.
129         * Follow the particular operation's effect, pending-state and reconciliation contract; do not automatically
130         * repeat a code redemption, rotating refresh, callback, credential mutation or application action.
131         *
132         * @return whether this failure is classified as a temporary condition
133         * @since 1.0.0
134         */
135        @NonNull
136        public final Boolean isTemporaryCondition() {
137                return this.transientFailure;
138        }
139
140        private static @NonNull String checkedMessage(@NonNull ErrorCategory category,
141                                                                                                                                                         @NonNull Boolean transientFailure,
142                                                                                                                                                         @NonNull String fixedMessage,
143                                                                                                                                                         @Nullable Throwable cause) {
144                requireNonNull(category);
145                requireNonNull(transientFailure);
146                requireNonNull(fixedMessage);
147
148                if (fixedMessage.isBlank())
149                        throw new IllegalArgumentException("A Revetsec exception message must not be blank.");
150
151                if (transientFailure && category != ErrorCategory.TRANSPORT && category != ErrorCategory.REMOTE_ERROR)
152                        throw new IllegalArgumentException("Only TRANSPORT and REMOTE_ERROR failures may be transient.");
153
154                if (cause != null && (category != ErrorCategory.TRANSPORT || !(cause instanceof IOException)))
155                        throw new IllegalArgumentException("Only a TRANSPORT failure may keep a cause, and it must be an "
156                                        + "IOException.");
157
158                return fixedMessage;
159        }
160}