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.oauth.server;
018
019import static java.util.Objects.requireNonNull;
020
021import com.google.errorprone.annotations.CheckReturnValue;
022import com.revetsec.internal.ConcurrentLruMap;
023import com.revetsec.internal.Limits;
024import com.revetsec.internal.http.Deadline;
025
026import org.jspecify.annotations.NonNull;
027import org.jspecify.annotations.Nullable;
028
029import java.time.Duration;
030import java.util.List;
031import java.util.Optional;
032import java.util.concurrent.TimeUnit;
033import java.util.concurrent.locks.ReentrantLock;
034
035import javax.annotation.concurrent.ThreadSafe;
036
037/**
038 * Bounded single-process optional cache with timed interruptible locking and approximate LRU
039 * eviction. The reused map is private: all access is serialized, entries are evicted before
040 * insertion and every mutation drains its bounded maintenance work. No listener, loader, worker
041 * thread or general map is exposed. There are at most maximumEntries retained records, each
042 * syntax-bounded to a 16384-byte encrypted envelope. Reads/replacements cost bounded local work;
043 * lock waits consume the supplied budget. Expiry/freshness is checked by the core before use, not
044 * asserted by this storage cache. It may evict at any time and has no durability. Sharing one
045 * instance shares only in-process storage; separate factories return separate caches. Applications
046 * may supply a distributed implementation through the metadata policy's cache option.
047 * The raw reused map has only a maintenance capacity target under concurrent writes. This wrapper
048 * supplies the strict entry bound; keep its map private and every access under its budgeted lock.
049 *
050 * @author <a href="https://www.revetkn.com">Mark Allen</a>
051 * @since 1.0.0
052 */
053@ThreadSafe
054@CheckReturnValue
055public final class InMemoryOAuthClientMetadataCache implements OAuthClientMetadataCache {
056    private final int maximumEntries;
057    private final @NonNull ReentrantLock lock;
058    private final @NonNull
059            ConcurrentLruMap<
060                    @NonNull OAuthClientMetadataCacheKey, @NonNull OAuthClientMetadataCacheEntry>
061            entries;
062
063    private InMemoryOAuthClientMetadataCache(int maximumEntries) {
064        this(maximumEntries, new ReentrantLock(), new ConcurrentLruMap<>(maximumEntries));
065    }
066
067    InMemoryOAuthClientMetadataCache(
068            int maximumEntries,
069            @NonNull ReentrantLock lock,
070            @NonNull ConcurrentLruMap<
071                            @NonNull OAuthClientMetadataCacheKey,
072                            @NonNull OAuthClientMetadataCacheEntry>
073                    entries) {
074        this.maximumEntries = Limits.CIMD_MAXIMUM_CACHE_ENTRIES.require(maximumEntries);
075        this.lock = requireNonNull(lock);
076        this.entries = requireNonNull(entries);
077        if (entries.capacity() != this.maximumEntries)
078            throw new IllegalArgumentException("Cache storage capacity does not match its bound.");
079    }
080
081    /**
082     * Constructs a fresh cache with the reviewed 128-entry default and no callback or thread
083     * startup.
084     *
085     * @return the fresh local cache
086     * @since 1.0.0
087     */
088    public static @NonNull InMemoryOAuthClientMetadataCache fromDefaults() {
089        return fromMaximumEntries(Limits.CIMD_MAXIMUM_CACHE_ENTRIES.getDefaultIntValue());
090    }
091
092    /**
093     * Constructs a fresh cache with a capacity from 1 through 4096, inclusive. This is local capacity
094     * across all its keys.
095     *
096     * @param maximumEntries the entry limit
097     * @return the fresh local cache
098     * @throws NullPointerException if maximumEntries is null
099     * @throws IllegalArgumentException if outside the allowed interval
100     * @since 1.0.0
101     */
102    public static @NonNull InMemoryOAuthClientMetadataCache fromMaximumEntries(
103            @NonNull Integer maximumEntries) {
104        return new InMemoryOAuthClientMetadataCache(
105                Limits.CIMD_MAXIMUM_CACHE_ENTRIES.require(requireNonNull(maximumEntries)));
106    }
107
108    /**
109     * Returns the local retained-entry bound.
110     *
111     * @return the bound
112     * @since 1.0.0
113     */
114    public @NonNull Integer getMaximumEntries() {
115        return this.maximumEntries;
116    }
117
118    /** {@inheritDoc}
119     * @since 1.0.0
120     */
121    @Override
122    public @NonNull Optional<@NonNull OAuthClientMetadataCacheEntry> read(
123            @NonNull OAuthClientMetadataCacheKey key, @NonNull Duration remainingBudget) {
124        requireNonNull(key);
125        Deadline deadline = budget(remainingBudget);
126        acquire(deadline);
127        try {
128            check(deadline);
129            OAuthClientMetadataCacheEntry entry = this.entries.get(key);
130            check(deadline);
131            return Optional.ofNullable(entry);
132        } finally {
133            this.lock.unlock();
134        }
135    }
136
137    /** {@inheritDoc}
138     * @since 1.0.0
139     */
140    @Override
141    public @NonNull Boolean compareAndSet(
142            @NonNull OAuthClientMetadataCacheKey key,
143            @Nullable String expectedVersion,
144            @Nullable OAuthClientMetadataCacheEntry replacement,
145            @NonNull Duration remainingBudget) {
146        requireNonNull(key);
147        if (expectedVersion != null) OAuthStoreFormat.nonce(expectedVersion);
148        if (replacement != null
149                && (!key.equals(replacement.getKey())
150                        || replacement.getVersion().equals(expectedVersion)))
151            throw new IllegalArgumentException("Invalid client metadata cache replacement.");
152        Deadline deadline = budget(remainingBudget);
153        acquire(deadline);
154        try {
155            check(deadline);
156            OAuthClientMetadataCacheEntry current = this.entries.get(key);
157            boolean matches =
158                    current == null
159                            ? expectedVersion == null
160                            : current.getVersion().equals(expectedVersion);
161            check(deadline);
162            if (!matches) return false;
163            if (replacement == null) {
164                this.entries.remove(key);
165                this.entries.drain();
166            } else {
167                if (current == null && this.entries.size() >= this.maximumEntries) {
168                    List<OAuthClientMetadataCacheKey> order = this.entries.keysInAccessOrder();
169                    this.entries.remove(order.get(order.size() - 1));
170                    this.entries.drain();
171                }
172                this.entries.put(key, replacement);
173                this.entries.drain();
174            }
175            check(deadline);
176            return true;
177        } finally {
178            this.lock.unlock();
179        }
180    }
181
182    private static @NonNull Deadline budget(@NonNull Duration remainingBudget) {
183        requireNonNull(remainingBudget);
184        if (remainingBudget.isZero() || remainingBudget.isNegative())
185            throw new IllegalArgumentException("A positive cache operation budget is required.");
186        return Deadline.fromNow(remainingBudget);
187    }
188
189    private void acquire(@NonNull Deadline deadline) {
190        check(deadline);
191        try {
192            if (!this.lock.tryLock(Math.max(1, deadline.remainingNanos()), TimeUnit.NANOSECONDS))
193                throw OAuthClientMetadataCacheException.fromReason(
194                        OAuthClientMetadataCacheException.Reason.TIMEOUT);
195        } catch (InterruptedException failure) {
196            Thread.currentThread().interrupt();
197            throw OAuthClientMetadataCacheException.fromReason(
198                    OAuthClientMetadataCacheException.Reason.INTERRUPTED);
199        }
200    }
201
202    private static void check(@NonNull Deadline deadline) {
203        if (Thread.currentThread().isInterrupted())
204            throw OAuthClientMetadataCacheException.fromReason(
205                    OAuthClientMetadataCacheException.Reason.INTERRUPTED);
206        if (deadline.isExpired())
207            throw OAuthClientMetadataCacheException.fromReason(
208                    OAuthClientMetadataCacheException.Reason.TIMEOUT);
209    }
210
211    @NonNull ReentrantLock lockForTests() {
212        return this.lock;
213    }
214
215    int sizeForTests() {
216        this.lock.lock();
217        try {
218            return this.entries.size();
219        } finally {
220            this.lock.unlock();
221        }
222    }
223
224    /** Returns a fixed description with no stored data.
225     * @return the redacted description
226     * @since 1.0.0
227     */
228    @Override
229    public @NonNull String toString() {
230        return "InMemoryOAuthClientMetadataCache{storage=<redacted>}";
231    }
232}